Hi,
I am having a 400 error when I am trying to save my playlist. I have been staring at this for 4 days and am coming up with nothing. Here is my code if anyone can have a look, I need another set of eyes on this, any help would be appreciated.
I am seeing all the data of the tracks being added to the playlist and everything working up until the final fetch line of the savePlaylist function in Spotify.js
Here is the specific error I am seeing
{"error" : { "status" : 400, "message" : "Error parsing JSON." } }
Spotify.js
const Spotify = {
getAccessToken() {
if (accessToken) {
return accessToken;
}
//check for an access token match
const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);
if (accessTokenMatch && expiresInMatch) {
accessToken = accessTokenMatch[1];
const expiresIn = Number(expiresInMatch[1]);
//clears the parameters and allows to get a new access token when it expires
window.setTimeout(() => (accessToken = ''), expiresIn * 1000);
window.history.pushState('Access Token', 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;
}
},
search(searchTerm) {
const accessToken = Spotify.getAccessToken();
return fetch(
`https://api.spotify.com/v1/search?type=track&q=${searchTerm}`,
{
headers: { Authorization: `Bearer ${accessToken}` },
}
)
.then((response) => {
return response.json();
})
.then((jsonResponse) => {
if (jsonResponse.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,
}));
} else {
return [];
}
});
},
savePlaylist(playlistName, uriArray) {
if (!playlistName || !uriArray.length) {
return;
}
const accessToken = Spotify.getAccessToken();
const headers = {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
};
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: playlistName, public: true }),
})
.then((response) => response.json())
.then((jsonResponse) => {
const playlistID = jsonResponse.id;
console.log(
`Playlist ID: ${playlistID} \n UserID: ${userID} \n First track Artist: ${uriArray[0].artist} \n Track length: ${uriArray.length}`
);
return fetch(
`https://api.spotify.com/v1/users/${userID}/playlists/${playlistID}/tracks`,
{
headers: headers,
method: 'POST',
body: JSON.stringify({ uris: uriArray }),
json: true,
}
);
});
});
},
};
App.js
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
searchBarTerm: '',
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);
this.setSearch = this.setSearch.bind(this);
}
addTrack(track) {
const playlistArray = this.state.playlistTracks;
const found = playlistArray.find((element) => {
return element.id === track.id;
});
if (found === undefined) {
this.state.playlistTracks.push(track);
this.setState({ playlistTracks: playlistArray });
console.log(
`The track named "${track.name}" has been added to the playlist`
);
} else {
console.log(
`The track named "${track.name}" already exist in the playlist`
);
}
}
removeTrack(track) {
let index;
const playlistArray = this.state.playlistTracks;
playlistArray.forEach((element) => {
if (track.id === element.id) {
index = playlistArray.indexOf(element);
playlistArray.splice(index, 1);
}
});
this.setState({ playlistTracks: playlistArray });
console.log(
`The track named "${track.name}" has been removed from the playlist`
);
}
updatePlaylistName(name) {
this.setState({ playlistName: name });
}
savePlaylist() {
const trackURIs = this.state.playlistTracks;
const playlistName = this.state.playlistName;
Spotify.savePlaylist(playlistName, trackURIs);
console.log(`Playlist Tracks to save: ${trackURIs}`);
}
search(searchTerm) {
Spotify.search(searchTerm).then((searchResults) => {
this.setState({ searchResults: searchResults });
});
}
setSearch(term) {
this.setState({ searchBarTerm: term });
}
render() {
return (
<div>
<h1>
Ja<span className="highlight">mmm</span>ing
</h1>
<div className="App">
<SearchBar
onSearch={this.search}
setSearch={this.setSearch}
searchBarTerm={this.state.searchBarTerm}
/>
<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;