Details:
I am developing a React application that integrates with the Spotify API to allow users to create and save playlists to their Spotify accounts.
The app has the following features:
Search for Songs: Users can search for songs using the Spotify API.
Add to Playlist: Users can add songs to a custom playlist.
Save to Spotify: Users can save their custom playlist to their Spotify account by providing a playlist name and clicking a “Save To Spotify” button.
Problem:
When attempting to save the playlist to Spotify, I encounter the following errors in the console:
Error making request to Spotify API /
Error saving playlist /
Failed to fetch
Context:
React Components:
SearchResults: Handles displaying search results and adding songs to the playlist.
Playlist: Manages the custom playlist, including removing tracks and saving the playlist to Spotify.
SpotifyAuth Module:
Handles authentication with Spotify using the Implicit Grant Flow.
Manages access tokens, including storing and retrieving them from localStorage.
Makes authenticated requests to the Spotify API.
Code for App.js
import React, { useState, useEffect } from "react";
import SpotifyAuth from "./components/SpotifyAuth";
import styles from "./App.css";
import SearchResults from "./components/SearchResults";
import Playlist from "./components/Playlist";
function App() {
const [songs, setSongs] = useState([]);
const [searchQuery, setSearchQuery] = useState("");
const [filteredSongs, setFilteredSongs] = useState([]);
const [playlistName, setPlaylistName] = useState("");
const [playlist, setPlaylist] = useState([]);
useEffect(() => {
// Handle authentication on mount
SpotifyAuth.getAccessToken();
}, []);
// Handle function for search input
const handleInputChange = async (e) => {
const searchQuery = e.target.value;
setSearchQuery(searchQuery);
if (searchQuery) {
try {
const response = await SpotifyAuth.makeRequest(`https://api.spotify.com/v1/search?q=${searchQuery}&type=track`);
const tracks = response.tracks.items.map((track) => ({
id: track.id,
title: track.name,
artist: track.artists[0].name,
album: track.album.name,
uri: track.uri
}));
setFilteredSongs(tracks);
} catch (error) {
console.error('Error fetching search results:', error);
}
} else {
setFilteredSongs([]);
}
};
const handleSearch = (e) => {
e.preventDefault();
};
// Handle function for playlist input
function handleChange(e) {
setPlaylistName(e.target.value);
};
const isTrackInPlaylist = (track) => {
return playlist.some((item) => item.id === track.id);
};
const addTrackToPlaylist = (track) => {
if (!isTrackInPlaylist(track)) {
setPlaylist([...playlist, track]);
}
};
const removeTrackFromPlaylist = (trackId) => {
setPlaylist(playlist.filter((track) => track.id !== trackId));
};
const handleSavePlaylist = async () => {
if (playlistName) {
try {
const userIdResponse = await SpotifyAuth.makeRequest('https://api.spotify.com/v1/me');
const userId = userIdResponse.id;
const createPlaylistResponse = await SpotifyAuth.makeRequest(`https://api.spotify.com/v1/users/${userId}/playlists`, {
method: 'POST',
body: JSON.stringify({
name: playlistName,
public: true
})
});
const playlistId = createPlaylistResponse.id;
const addTracksResponse = await SpotifyAuth.makeRequest(`https://api.spotify.com/v1/playlists/${playlistId}/tracks`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${SpotifyAuth.getAccessToken()}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
uris: playlist.map(track => track.uri)
})
});
console.log('Add Tracks Response:', addTracksResponse);
setPlaylist([]);
setPlaylistName("");
alert("Playlist saved!", playlist);
} catch(error) {
console.error('Error saving playlist:', error);
if(error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.error('Response data:', error.response.data);
console.error('Response status:', error.response.status);
console.error('Response headers:', error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.error('Request data:', error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.error('Error message:', error.message);
}
alert('Failed to save playlist.');
}
} else {
alert("Please enter a playlist name.");
}
};
return (
<div className="App">
<header>
<h1>JAMMMING</h1>
<h3>Spotify Playlist Maker</h3>
</header>
<main>
<SearchResults
searchQuery={searchQuery}
handleInputChange={handleInputChange}
filteredSongs={filteredSongs}
handleSearch={handleSearch}
onAdd={addTrackToPlaylist}
/>
<Playlist
playlistName={playlistName}
handleChange={handleChange}
playlist={playlist}
onRemove={removeTrackFromPlaylist}
handleSavePlaylist={handleSavePlaylist}
/>
</main>
</div>
);
}
export default App;
Code for SpotifyAuth Component
const clientId = 'MY_CLIENT_ID';
const redirectUri = 'http://localhost:3000';
const scopes = [
'playlist-modify-public',
'playlist-modify-private'
];
const getTokenFromUrl = () => {
const params = new URLSearchParams(window.location.hash.replace('#', ''));
const accessToken = params.get('access_token');
const expiresIn = params.get('expires_in');
return { accessToken, expiresIn };
};
const SpotifyAuth = {
getAccessToken: () => {
const tokenData = getTokenFromUrl();
if (tokenData.accessToken) {
const expirationTime = new Date().getTime() + (tokenData.expiresIn * 1000);
localStorage.setItem('spotify_access_token', tokenData.accessToken);
localStorage.setItem('spotify_token_expiration', expirationTime);
// Clear URL parameters
window.history.pushState({}, null, '/');
return tokenData.accessToken;
}
const accessToken = localStorage.getItem('spotify_access_token');
const expirationTime = localStorage.getItem('spotify_token_expiration');
if (accessToken && new Date().getTime() < expirationTime) {
return accessToken;
} else {
SpotifyAuth.redirectForAuth();
}
},
redirectForAuth: () => {
const authUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${encodeURIComponent(scopes.join(' '))}`;
window.location.href = authUrl;
},
makeRequest: async (url, options = {}) => {
const accessToken = SpotifyAuth.getAccessToken();
if (!accessToken) {
throw new Error('Access token not found');
}
const headers = {
...options.headers,
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json'
};
try {
const response = await fetch(url, { ...options, headers });
if (!response.ok) {
const errorResponse = await response.json();
console.error('Error response from Spotify API:', errorResponse);
throw new Error('Spotify API request failed' + errorResponse.error.message);
}
return response.json();
} catch (error) {
console.error('Error making request to Spotify API:', error);
throw error;
}
}
};
export default SpotifyAuth;
Troubleshooting Steps Taken:
Error Handling:
Added try-catch blocks around the API requests to capture and log any errors.
Implemented error messages to display to the user when something goes wrong.
DevTools Inspection:
Used Chrome DevTools to inspect network requests and ensure that they are being sent correctly.
Verified that the access token is being retrieved and included in the request headers.
What Actually Resulted
Saving the Playlist:
When trying to save the playlist, the following errors are logged in the console:
Error making request to Spotify API
Error saving playlist
Failed to fetch
The playlist is not being saved to the user’s Spotify account.
The errors suggest an issue with making the API requests, but the specific cause is unclear. Possible issues could be with token management, request headers, or the structure of the API requests.
Despite these efforts, the errors still persist, and the playlist is not being saved to the user’s Spotify account. Any guidance on diagnosing and fixing these issues would be greatly appreciated!
Ailee Chang is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.