Jammming Save Playlist is Not Working

Hello everyone! Well I have been trying to solve this problem for a week now, but I cannot find any solution to this problem.
The problem I have is that I cannot “save the playlist” to Spotify. I have tried to console the problem and this is what I get.

As you can see, the error I get is when the promise return to get the “userId” and the “playlistId”.

I have watched the project walkthrough many times, but I cannot get my project to work.

Here I attach my code.

const clientId = 'ACCESS-TOKEN'
const redirectUri = 'http://localhost:3000/';

let accessToken;

const Spotify = {
        getAccessToken(){
            if(accessToken){
                return accessToken
            }

            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])

                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;
            }
        },

        async search(term){
            const accessToken = Spotify.getAccessToken();
            const response = await fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`,
                {
                    headers: {
                        Authorization: `Bearer ${accessToken}`
                    }
                });
            const jsonResponse = await response.json();
            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
            }));
        },

        savePlaylist(name, tracksUris){
            if(!name || !tracksUris.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 => response.json()
            ).then(jsonResponse => {
                userId = jsonResponse.id;
LINE 63 --->     return fetch(`https://api.spotify.com/v1/users/${userId}/playlist`,
                {
                    headers: headers,
                    method: 'POST',
                    body: JSON.stringify({name: name})
                }).then(response => response.json()
                ).then(jsonResponse => {
                    const playlistId = jsonResponse.id;
LINE 71 --->      return fetch(`https://api.spotify.com/v1/users/${userId}/playlists/${playlistId}/tracks`,
                    {
                        headers: headers,
                        method: 'POST',
                        body: JSON.stringify({uris: tracksUris})
                    })
                })
            })
        }
}

export default Spotify;

I kindly request your support.

The problem not caused by the Spotify helper functions you posted. The error message indicates that you use onSearch as an event handler rather than as props in the SearchBar Component.

onSearch should be passed as props from App.js to Searchbar.js. It should contain the function ‘search’ which you defined in the App component and be called in the SearchBar component by the search button. The button does not recognize the on Search event, it should rather be an onClick event.

Hello mirja_t,

Your were right, now I deleted that 'onSearch", but I keep getting those errors as I show you in the image bellow

What does this log:

savePlaylist(name, tracksUris){
            if(!name || !tracksUris.length){
                return
            }
console.log(name, tracksUris)

?

it gave me the following

It’s a tiny little typo in the url:

This:

should be this:

return fetch(`https://api.spotify.com/v1/users/${userId}/playlists`,

Plural.

1 Like

Thank you very much! @mirja_t :heart: :100:

1 Like