I am trying to obtain a reply (a track list (json)) from the spotify API but I keep getting this error:
{status: 400, message: "No search query"}
this is my function in my spotify.api module:
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,
}));
});
},
This is app.js (main container component) where the state is at; these are within the class react constructor:
search(term) {
Spotify.search(term).then(searchResults => {
this.setState({
searchResults: searchResults
})
})
}
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 searchBar.js component, where the input (or track) will be requested:
search() {
this.props.onSearch(this.state.term);
}
handleTermChange(event) {
this.setState = { term: event.target.value };
}
render() {
return (
<div className="SearchBar">
<input
onChange={this.handleTermChange}
placeholder="Enter A Song, Album, or Artist"
/>
<button className="SearchButton" onClick={this.search}>SEARCH</button>
</div>
);
}
}
Try changing this
handleTermChange(event) {
this.setState = { term: event.target.value };
}
To
handleTermChange(event) {
this.setState({ term: event.target.value });
}
Since you were not using the setState method correctly, you were calling the Spotify API with an empty term value, then you get the http 400 error.