Search code examples
reactjsapipostsavespotify

Not able to save my new playlist in my Spotify account (I get an empty list of tracks)


This is my function in my util module Spotify:


savePlaylist1(name, trackUris) {
    if (!name || !trackUris.length) {
      return;
    }
    const accessToken = Spotify.getAccessToken();
    const headers = { Authorization: `Bearer ${accessToken}` };


    let userID;
    return fetch('https://api.spotify.com/v1/me', { headers: headers }
    ).then(response => {
      return 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: name })
      }).then(response => {
        return response.json();
      }).then(jsonResponse => {
        const playlistID = jsonResponse.id;
        return fetch(`https://api.spotify.com/v1/playlists/${playlistID}/tracks`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${accessToken}`,
          },
          body: JSON.stringify({ uris: trackUris })
        })
      })
    })
  } // end of savePlaylist1 method
}

This is my container module where I'm calling the function from: (followed by the render function)


savePlaylist() {
    const trackUris = this.state.playlistTracks.map(track => track.uri);
    Spotify.savePlaylist1(this.state.playlistName, trackUris).then(() => {
      this.setState({
        playlistName: 'New Playlist',
        playlistTracks: []
      });
    })
  }


 render() {
    return (
      <div>
        <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>);
  }

this is the playlist component with the safe button>


render() {
    return (
      <div className="Playlist">
        <input defaultValue={"New Playlist"} onChange={this.handleNameChange} />
        <TrackList
          tracks={this.props.playlistTracks}
          onRemove={this.props.onRemove}
          isRemoval={true}
        />
        <button className="Playlist-save" onClick={this.props.onSave}>
          SAVE TO SPOTIFY
        </button>
      </div>
    );
  }

it is saving with an empty list and I get the following error:

{ "error" : { "status" : 400, "message" : "Invalid track uri: null" } }


Solution

  • Finally, this is the jamming project in codecademy, the problem was that it was not loading the URIs, when being called from the API, this was because it was not included in the search function as part of the list:

    search(term) {
        const accessToken = Spotify.getAccessToken();
        return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
          headers: {
            Authorization: `Bearer ${accessToken}`,
          },
        }).then(response => {
          return response.json();
        }).then(jsonResponse => {
          if (!jsonResponse.tracks) {
            return [];
          }
          return jsonResponse.tracks.items.map(track => ({
            id: track.id,
            name: track.name,
            artist: track.artists[0].name,
            album: track.album.name,
            uri: track.uri //this was missing!!!!
          }));
        });
      },