Jamming project, tracks don't get displayed

Practice Project: Jammming | Codecademy

I’ve got to the end of the project and everything seemed to be fine, but once I tried to search the tracks nothing appears. If someone could help me by telling me what I did wrong and also maybe a way to learn and not repeat the same mistake I would appreciate it. I followed a bit of the walkthrough at the end because I was struggling a little with certain stuff but even then a mistake must of been made.

Spotify.js

import React from 'react';
import Playlist from '../Components/Playlist/Playlist';
let userToken;
const clientID = 'ee3c1d7c21754336a8f9d81682e1c8c6';
const redirectURI = "http://localhost:3000/";
const Spotify = {
    getAccessToken() {
        if (userToken) {
            return userToken;
        }

        const userTokenMatch = window.location.href.match(/access_token=([^&]*)/);
        const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);

        if(userTokenMatch && expiresInMatch) {
            userToken = userTokenMatch[1];
            let expireTime = Number(expiresInMatch[1]); 
            window.setTimeout(() => userToken = '', expireTime * 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(userSearch) {
        const userToken = Spotify.getAccessToken();
        return fetch(`https://api.spotify.com/v1/search?type=track&q=${userSearch}`, {
            headers: {
                Authorization: `Bearer ${userToken}`
            }
        }).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.artist[0].name,
                album: track.album.name,
                uri: track.uri
            }))
        })
    },
    playlistUri(playlistName, trackUris) {
        if(!playlistName || !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: playlistName})
            }).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({ uris: trackUris})
                })
            })
        })

    }
}
 
export default Spotify;

and App.js

type or paste code here

I understand that the app.js code isnt showing up, but on the computer it gives me “403 Error” so i’m not being able to fix it.

Have you already tried to add consoles to the Spotify method in order to see where you don’t get a valid response anymore? That’s how I would do it. I would put a console to each step, log the variables and see which one comes back undefined.
And also: do you get already an error message in the console?

1 Like

I do not get any errors on the console, i’ll attempt to console.log each step to console later on. Thank you for your suggestion. If i get any new information I’ll make a new reply.

1 Like

I havent gotten it to work yet, Ive spent quite a lot of time, when I add console.log inside the Spotify object nothing appears on the console, no errors are displayed either on the console ever.

I do not know why it doesn’t let me post the code, it gives me 403 error, but normal messages like this it lets me.

These 403 errors are a known issue CC hasn’t solved yet, unfortunately. Maybe you could post it here to raise some attention for this.
Do you have git repo? Can you add the component there – with all consoles you added?

I’ve removed the consoles but i’ll re add them and post it on a git hub repo to share it

Just add the first since that part of the code wasn’t even reached.

Im sorry if this wasnt what you were looking for but I had already added once i saw your message, i thank you for your help.

The App calls the search method of the Spotify class. So the first line executed (if at all) is this:

search(term) {
        const accessToken = Spotify.getAccessToken();

So add your first 2 consoles here:

search(term) {
console.log(term)
        const accessToken = Spotify.getAccessToken();
console.log(accessToken)

Do you see anything in the console?

I do not, all of this makes me think that Spotify.js isn`t being called however I do not see the error.

If even this console.log(term) doesn’t log anything, then yes…

Does this log anything?

search(term) {
    Spotify.search(term).then(searchResults => {
      // this.setState({ searchResults: searchResults})
      console.log(this.state.searchResults)
    });
  }

It does not log anything onto the console. After checking the React components on the dev tools, I have onSearch prop bound to search() on the SearchBar. Also the term updates when I type, this tells me that it’s working however something is clearly not working since it doesn`t even log anything into the console.

This is the way to track the error down. If it doesn’t log anything, have a look where you pass the method and where you call it. It turns out that the search method is never called in the SearchBar component. This button doesn’t do anything:

<button className="SearchButton">SEARCH</button>

I did notice this after sending the last message and I`ve been testing, I added the following console :

search(term) { Spotify.search(term).then(searchResults => { // this.setState({ searchResults: searchResults}) console.log(this.state.searchResults) }); }

And also added a "

Also added a onClick that once clicked activates this.search, now it logs an empty array to the console. Im having a lot of issues with CC so sorry for not being able to explain it well

The codebyte shows the same code as before and you did not update your repo, so I don’t see which console you’re talking about.

Ill update the repo to make it easier since CC isn’t working

I’m out for today. I’ll have a look at it tomorrow.

No problem, thank you alot for your help, i`m also really tired, have spent majority of the day on it. If I end up finding any update in the mean time ill update the Repo and leave a message here explaining it if needed.

1 Like