Jamming - Search unresponsive

I seem to have gotten to the end, however when searching for songs nothing appears in the search results. I would appreciate any help given, thank you.

App.js

import React from 'react';
import './App.css';

import SearchBar from '../SearchBar/SearchBar';
import SearchResults from '../SearchResults/SearchResults';
import Playlist from '../Playlist/Playlist';
import Spotify from '../../util/Spotify';

class App extends React.Component {
  
  constructor (props) {
    super(props);

    this.state = {
      searchResults: [],
      playlistName: 'New Playlist',
      playlistTracks: []
    };
    this.addTrack = this.addTrack.bind(this);
    this.removeTrack = this.removeTrack.bind(this);
    this.updatePlaylistName = this.updatePlaylistName.bind(this);
    this.savePlaylist = this.savePlaylist.bind(this);
    this.search = this.search.bind(this);
  }
  
  addTrack (track) {
    let tracks = this.state.playlistTracks;
    if (tracks.find(savedTrack => savedTrack.id === track.id)) {
      return;
    }

    tracks.push(track);
    this.setState({ playlistTracks: tracks });
  }

  removeTrack (track) {
    let tracks = this.state.playlistTracks;
    tracks = tracks.filter(selectedTrack => selectedTrack.id !== track.id );

    this.setState({ playlistTracks: tracks });
  }

  updatePlaylistName (name) {
    this.setState({playlistName: name});
  }

  savePlaylist () {
    const trackUris = this.state.playlistTracks.map(track => track.uri);
    Spotify.savePlaylist(this.state.playlistName, trackUris).then(() => /* will clear playlist and playlist name once playlist has been saved */ {
      this.setState({ 
        playlistName: 'New Playlist',
        playlistTracks: []
      })
    })
  }

  search (searchItem) {
    Spotify.search(searchItem).then(searchResults => /* set searchResults to results from spotify */ {
      this.setState({searchResults: searchResults});
    })
  }

  render () {
    return (
    <div>
  <h1>Play<span className="highlight">mixer</span></h1>
  <div className="App">
    <SearchBar onSearch={this.search} />
    <div className="App-playlist">
      <SearchResults searchResults={this.state.searchResults} onAdd={this.addTrack} />
      <Playlist playlistName={this.state.playlistName} 
                playlistTracks={this.state.playlistTracks} 
                onRemove={this.removeTrack} 
                onNameChange={this.updatePlaylistName} 
                onSave={this.savePlaylist} />
    </div>
  </div>
</div>
    )
  }
}

export default App;

Spotify.js

const clientId = 'bb1e09fa2aaa422f8044418fa47ca202';
const redirectUri = 'http://localhost:3000/';


let accessToken;

const Spotify = {
    getAccessToken() {
        if (accessToken) {
            return accessToken;
        }
        // access token match check
        const accessTokenCheck = window.location.href.match(/access_token=([^&]*)/);
        const expiresInCheck = window.location.href.match(/expires_in=([^&]*)/);

        if (accessTokenCheck && expiresInCheck) {
            accessToken = accessTokenCheck[1];
            const expiresIn = Number(expiresInCheck[1]);

        // This will allow new access token when previous one expires

            window.setTimeout(() => accessToken = '', expiresIn * 1000);
            window.history.pushState('accessToken', null, '/');
            return accessToken;
        } else {
            const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`;
            window.location = accessUrl;
        }
        },

    // Allows user to search spotify using spotify fetch method with access token
    search(searchItem) {
        const accessToken = Spotify.getAccessToken();
        const headers = { Authorization: `Bearer ${accessToken}`};
        return fetch(`https://api.spotify.com/v1/search?type=track&q=${searchItem}`, 
            { headers: headers }
            ).then(response => {
                // converting response to json 
                return response.json()
            }).then(jsonResponse => {
                if (!jsonResponse.tracks) /* checks if there are no tracks */ {
                    return [];
                } /* else it will convert json to an array of tracks */
                return jsonResponse.tracks.items.map(track => ({
                    id: track.id,
                    name: track.name,
                    artist: track.artists[0].name,
                    album: track.album.name,
                    uri: track.uri
                }));
            });
    },

    savePlaylist(playlistName, trackUris) {
        if (!playlistName || !trackUris.length) /* checks if there is a playlistname or any tracks added */ {
            return;
        } 
        const accessToken = Spotify.getAccessToken();
        const headers = { Auhtorization: `Bearer ${accessToken}`};
        let userId;

        return fetch('https://api.spotify.com/v1/me', {headers: headers}
        ).then(response => response.json()
        ).then(jsonResponse => {userId = jsonResponse.id;
            return fetch(`https://api.spotify.com/v1/users/${userId}/playlists`, 
            {
                headers: headers,
                method: 'POST',
                body: JSON.stringify({ name: playlistName})
            }).then(response => response.json()
            ).then(jsonResponse => {
                const playlistId = jsonResponse.id;
                /* use the userID to make a POST request to create new playlist */
                return fetch(`https://api.spotify.com/v1/users/${userId}/playlists/${playlistId}/tracks`, 
                {
                    headers: headers,
                    method: 'POST',
                    body: JSON.stringify({ uris: trackUris })
                })
            })
        });

    }

    };

export default Spotify;

SearchBar.js

import React from 'react';
import './SearchBar.css';

class SearchBar extends React.Component {
    
    constructor(props) {
        super(props);

        this.state = {
            searchItem: ''
        }

        this.search = this.search.bind(this);
        this.handleTermChange = this.handleTermChange.bind(this);
    }

    handleTermChange(event) {
        this.setState({ searchItem: event.target.value });
    }

    search () {
        this.props.search(this.state.searchItem);
    }
    
    render() {
        return (
            <div className="SearchBar">
                <input placeholder="Enter A Song, Album, or Artist" 
                        onChange={this.handleTermChange} />
                <button className="SearchButton">SEARCH</button>
            </div>
        )
    }
}
export default SearchBar;

SearchResults.js

import React from 'react';
import './SearchResults.css';

import TrackList from '../TrackList/TrackList';

class SearchResults extends React.Component {
    render () {
        return (
            <div className="SearchResults">
                <h2>Results</h2>
                <TrackList tracks={this.props.searchResults} 
                            onAdd={this.props.onAdd} 
                            isRemoval={false} />
            </div>
        )
    }
}

export default SearchResults;

Thank you again

Might be missing something here.

Hint

How does your button know to do anything when clicked?

1 Like