Jamming part one

Hi Guys,

I have completed the first part of the jamming project (link below) but i don’t appear to be getting any results when ii click search after typing a song title, link to my code also below, if someone could give me a few pointers that would be great!
https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-22-react-part-ii/modules/wdcp-22-jammming/projects/jammming-prj

1 Like

Hey Isaac,

Do you mind pasting the search function? Do you get any errors in the developer tools? Can you authenticate a user without problem?

Regards

Hi Joacopaz,
No errors on dev tools which is what is really throwing me tbh, see code below :slight_smile:

const clientId = ''


const redirectUri = 'http://localhost:3000/';

let accessToken;
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]);
            // this is going to clear the parameters, allowing us to grab a new access token when it expires.
            window.setTimeout(() => accessToken = '', expiresIn * 1000);
            window.history.pushState('Access Token', null, '/');
        } 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(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,
                url: track.uri
            }));
        })
    },
    savePlaylist(name, trackUris) { //having the ! means that we're saying if there are NO names or NO 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 => 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 => response.json()
            ).then(jsonResponse => {
                const playlistId = jsonResponse.id;
                return fetch(`https://api.spotify.com/v1/users/${userId}/playlists/${playlistId}/tracks`, { 
                    headers: headers,
                    method: 'POST',
                    body: JSON.stringify({uri: trackUris})
                })
            })
        })
    }
}

export default Spotify;
1 Like

Hey Isaac,

Apologies for the delay, just got on the pc.

I don’t see anything wrong with your code. It may be in the implementation in React. Did you try adding a bunch of console logs to every step of the search process search(term)? For example, console log the access token, and for every response in the fetch request console log the results before returning to see step by step what is happening behind the scenes?

And finally log the end jsonResponse.tracks to see what is returned.

If you want I can share my project/code but I made so many modifications over the original one I wouldn’t want to add more noise to the code.

I haven’t done this project, but just double-check whether

## You wrote:
...
album: track.album.name,
url: track.uri

## Is it supposed to be?
...
album: track.album.name,
uri: track.uri

Yes, the response is an object with a track and those properties are ok.

In my working project the search function reads as follows

async search(term) {
		const accessToken = Spotify.getAccessToken();
		const url = "https://api.spotify.com/v1";
		const endpoint = "/search?type=track&q=";
		const request = url + endpoint + term;
		const response = await fetch(request, {
			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,
		}));
	}

Does the following change make any difference?

getAccessToken(){
...
 window.history.pushState('Access Token', null, '/');
 return accessToken;        // <-----------Try adding this line
        } else {
1 Like

unfortunately not :frowning:

In the map, which of the two do you have?

url: track.uri

OR

uri: track.uri

again with this change, still no search results

changed from url to uri

In SearchBar.js, you have a search button.

Is there supposed to be an onClick attribute for this button?

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.