Spotify API Problem, Save to Playlist Throwing Errors

I’m doing the Jammming project and it has seemingly been above the level of what we’ve been doing so far, so I’m scrambling some. What I could use is some input on the error’s I’m getting when trying to save the name of the playlist I’m trying to create. I will include the Spotify API call and the App.js function that are both providing me errors.

My desired behavior is that this would stop throwing error’s when trying to use my ‘Save to Spotify’ button. My search bar works and calls on the API just fine, but this one is the problem.

// Spotify API Call

import React from 'react';

let userAccessToken = '';

const clientID = '**redacted**';
const redirectURI = `http://localhost:3000/`;

const Spotify = {
  getAccessToken() {
    // First check
    if (userAccessToken) return userAccessToken;

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

    // Second check for the access token
    if (token && expiry) {
      // Setting values for token and expiration time
      const userAccessToken = token[1];
      const expiresIn = Number(expiry[1]);

      // Setting the access token to expire at the value for expiration time
      window.setTimeout(() => (userAccessToken = ''), expiresIn * 1000);
      window.history.pushState('Access token', null, '/');

      // Returning the access token
      return userAccessToken;
    }

    //Redirect
    const redirect = `https://accounts.spotify.com/authorize?client_id=${clientID}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectURI}`;
    window.location = redirect;
  },

  // Search method
  search(term) {
    const accessToken = Spotify.getAccessToken();
    return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
      headers: { Authorization: `Bearer ${accessToken}` },
    })
      .then((response) => response.json())
      .then((jsonResponse) => {
        if (!jsonResponse) {
          console.error('Response error!');
        }
        return jsonResponse.tracks.items.map((t) => ({
          id: t.id,
          name: t.name,
          artist: t.artists[0].name,
          album: t.album.name,
          uri: t.uri,
        }));
      }); // Second .then() statement
  }, // getAccessToken function

  savePlaylist(name, trackUris) {
    if (!name || !trackUris) {
      throw new Error('Please provide a name');
    } else {
      const aToken = Spotify.getAccessToken();
      const header = { Authorization: `Bearer ${aToken}` };
      let userId;
      return fetch('https://api.spotify.com/v1/me', { headers: header })
        .then((response) => response.json())
        .then((jsonResponse) => {
          userId = jsonResponse.id;
          let playlistId;
          return fetch(`https://api.spotify.com/v1/users/${userId}/playlists`, {
            headers: header,
            method: 'post',
            body: jsonResponse.stringify({ name: name }),
          })
            .then((response) => response.json())
            .then((jsonResponse) => {
              playlistId = jsonResponse.id;
              return fetch(
                `https://api.spotify.com/v1/playlists/${playlistId}/tracks`,
                {
                  headers: header,
                  method: 'post',
                  body: JSON.stringify({ uris: trackUris }),
                },
              );
            });
        });
    }
  },
}; // Spotify Initializer

export { Spotify };
// App.js Function

function savePlaylist(trackUris) {
  const TrackURIs = playlistTracks?.map((track) => track.uri);
  return Spotify.savePlaylist(playlistName, TrackURIs)
    .then(() => {
      setPlaylistName('New Playlist');
      setPlaylistTracks([]);
    })
    .catch((error) => {
      alert(error);
    });
}

I’ve tried throwing and catching an error, I’ve ran it with breakpoints, I’ve refactored the if/else statement

Link to project: https://www.codecademy.com/journeys/front-end-engineer/paths/fecj-22-front-end-development/tracks/fecj-22-react-part-ii/modules/wdcp-22-jammming-b26fb9a6-a249-4dda-91a0-ebaa5c8de0ce/kanban_projects/jammming-react18

What errors does it throw?

Cannot read properties of undefined (reading ‘then’)
TypeError: Cannot read properties of undefined (reading ‘then’)
at savePlaylist (http://localhost:3000/main.53e3145dae3a220d9474.hot-update.js:64:107)
at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:10446:18)
at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:10490:20)
at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:10547:35)
at invokeGuardedCallbackAndCatchFirstError (http://localhost:3000/static/js/bundle.js:10561:29)
at executeDispatch (http://localhost:3000/static/js/bundle.js:14704:7)
at processDispatchQueueItemsInOrder (http://localhost:3000/static/js/bundle.js:14730:11)
at processDispatchQueue (http://localhost:3000/static/js/bundle.js:14741:9)
at dispatchEventsForPlugins (http://localhost:3000/static/js/bundle.js:14750:7)
at http://localhost:3000/static/js/bundle.js:14910:16

I’m also just trying to get full functionality of this Save to Playlist button. That’s my end goal.

Is that all? If you created the app using create-react-app, aren’t you seeing more, like ‘Please provide a name’? Are you trying to save an empty playlist?

Currently yes the playlist is empty and devoid of tracks (I’m trying to figure out why my ‘add to playlist’ button doesn’t have functionality). So should I work on adding songs to the playlist before I try to get on this?

I guess this is throwing the error because you get nothing returned from Spotify.savePlaylist currently. You could try to manually add one of your searchresults.