Jamming Project not working

Hello, I am doing the jamming project (https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-react-part-ii/modules/fecp-challenge-project-jammming/projects/jammming-prj) and I have just finished it. Unfortunately, it does not work. I get no errors, but when I search no songs come up.
This is the content of my App.js file:

import './App.css';

import React from 'react';

import SearchBar from '../SearchBar/SearchBar';

import SearchResults from '../SearchResults/SearchResults';

import Playlist from '../Playlist/Playlist';

import Spotify from '../../util/Spotify';

class App extends React.Component {

  constructor (props) {

    super (props);

    this.state = {

      searchResults: [],

       playlistName: 'My playlist',

       playlistTracks: []

     

    };

    this.addTrack = this.addTrack.bind(this);

    this.removeTrack = this.removeTrack.bind(this);

    this.updatePlaylistName = this.updatePlaylistName.bind(this);

    this.savePlaylist = this.savePlaylist.bind(this);

    this.search = this.search.bind(this);

  }

addTrack(track){

let tracks = this.state.playlistTracks;

if (tracks.find(savedTrack => savedTrack.id === track.id)){

  return;

}

tracks.push(track);

this.setState({playlistTracks: tracks});

}

removeTrack(track) {

  let tracks = this.state.playlistTracks;

  tracks = tracks.filter(currentTrack => currentTrack.id !== track.id);

  this.setState({playlistTracks: tracks});

}

updatePlaylistName(name) {

  this.setState({playlistName: name});

}

savePlaylist() {

  let trackUris = this.state.playlistTracks.map(track => track.uri);

  Spotify.savePlaylist(this.state.playlistName, trackUris).then(() => {

    this.setState({

     playlistName: 'New Playlist',

     playlistTracks: []

  })

})

}

search(term) {

Spotify.search(term).then(searchResults => {

this.setState({searchResults: searchResults})

})

}

    render () {

      return (

        <div>

        <h1>Ja<span className="highlight">mmm</span>ing</h1>

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

      )

    }

}

export default App;

And this is the content of my Spotify.js file:

const clientId = 'My access token';

let accessToken;

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

const Spotify = {

    getAccessToken() {

        if(accessToken) {

            return accessToken;

        }

        //check for access token match

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

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

        if (accessToken && expiresInMatch) {

            accessToken = accessTokenMatch[1];

            const expiresIn = Number(expiresInMatch[1]);

            //This clears the parameters, allowing us to grab a new access token when it expires

            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;

        }

    },

    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 [];

        }

        else {

            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, 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({ uris: trackUris })

                        })

                });

        })

    }

}

Does anyone know why it is not working ?

1 Like

Hi,
Please read this guide and format your code accordingly. That makes it easier for everyone to read your code and help you out.
I would recommend that you replace your access token in the post. That should not be public.

1 Like

Hey,

finding those unspecific errors is not an easy thing for anyone. Probably just few of the forum users find the cause of an error at first glance – especially if no error is thrown at you giving a hint. So you have to play detective.
Here are the game instructions:
Add a consoles at different places in your code. Start at the top of the Spotify.search method. This way you find out if the method is called in the first place and if so, if it receives a valid object.
If it logs the expected result, add further consoles to see where your chain is interrupted. In your case that’s a bit difficult, because the App always immediately reloads – an unexpected behaviour that gets us closer to the issue. It indicates that there is an issue in the getAccessToken() method.
Add consoles at all three conditions. You’ll see that the console added here always shows up for a millisecond:

Thats not how it should be. You want this code block to be entered after the first redirection:

Why isn’t it? And what should the condition for this block be?

Thank you so much! I have now found the error and fixed it. My project works just fine.

1 Like