Issue with Saving Playlist to Spotify API in React Application: “Failed to Fetch” Error

Details:

I am developing a React application that integrates with the Spotify API to allow users to create and save playlists to their Spotify accounts.

The app has the following features:

Search for Songs: Users can search for songs using the Spotify API.

Add to Playlist: Users can add songs to a custom playlist.

Save to Spotify: Users can save their custom playlist to their Spotify account by providing a playlist name and clicking a “Save To Spotify” button.

Problem:

When attempting to save the playlist to Spotify, I encounter the following errors in the console:

Error making request to Spotify API /
Error saving playlist /
Failed to fetch

Context:

React Components:

SearchResults: Handles displaying search results and adding songs to the playlist.
Playlist: Manages the custom playlist, including removing tracks and saving the playlist to Spotify.
SpotifyAuth Module:
Handles authentication with Spotify using the Implicit Grant Flow.
Manages access tokens, including storing and retrieving them from localStorage.
Makes authenticated requests to the Spotify API.

Code for App.js

import React, { useState, useEffect } from "react";
import SpotifyAuth from "./components/SpotifyAuth";
import styles from "./App.css";
import SearchResults from "./components/SearchResults";
import Playlist from "./components/Playlist";

function App() {
  const [songs, setSongs] = useState([]);
  const [searchQuery, setSearchQuery] = useState("");
  const [filteredSongs, setFilteredSongs] = useState([]);
  const [playlistName, setPlaylistName] = useState("");
  const [playlist, setPlaylist] = useState([]);

  useEffect(() => {
    // Handle authentication on mount
    SpotifyAuth.getAccessToken();
  }, []);

  // Handle function for search input
  const handleInputChange = async (e) => {
    const searchQuery = e.target.value;
    setSearchQuery(searchQuery);

    if (searchQuery) {
      try {
        const response = await SpotifyAuth.makeRequest(`https://api.spotify.com/v1/search?q=${searchQuery}&type=track`);
        const tracks = response.tracks.items.map((track) => ({
          id: track.id,
          title: track.name,
          artist: track.artists[0].name,
          album: track.album.name,
          uri: track.uri
        }));
        setFilteredSongs(tracks);
      } catch (error) {
        console.error('Error fetching search results:', error);
      }
    } else {
      setFilteredSongs([]);
    }
  };

  const handleSearch = (e) => {
    e.preventDefault();
  };

  // Handle function for playlist input
  function handleChange(e) {
    setPlaylistName(e.target.value);
  };
  
  const isTrackInPlaylist = (track) => {
    return playlist.some((item) => item.id === track.id);
  };

  const addTrackToPlaylist = (track) => {
    if (!isTrackInPlaylist(track)) {
      setPlaylist([...playlist, track]);
    }
  };

  const removeTrackFromPlaylist = (trackId) => {
    setPlaylist(playlist.filter((track) => track.id !== trackId));
  };

  const handleSavePlaylist = async () => {
    if (playlistName) {
      try {
        const userIdResponse = await SpotifyAuth.makeRequest('https://api.spotify.com/v1/me');
        const userId = userIdResponse.id;

        const createPlaylistResponse = await SpotifyAuth.makeRequest(`https://api.spotify.com/v1/users/${userId}/playlists`, {
          method: 'POST',
          body: JSON.stringify({
            name: playlistName,
            public: true
          })
        });

        const playlistId = createPlaylistResponse.id;

        const addTracksResponse = await SpotifyAuth.makeRequest(`https://api.spotify.com/v1/playlists/${playlistId}/tracks`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${SpotifyAuth.getAccessToken()}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            uris: playlist.map(track => track.uri)
          })
        });

        console.log('Add Tracks Response:', addTracksResponse);

        setPlaylist([]);
        setPlaylistName("");
        alert("Playlist saved!", playlist);
      } catch(error) {
        console.error('Error saving playlist:', error);

        if(error.response) {
          // The request was made and the server responded with a status code
          // that falls out of the range of 2xx
          console.error('Response data:', error.response.data);
          console.error('Response status:', error.response.status);
          console.error('Response headers:', error.response.headers);
        } else if (error.request) {
          // The request was made but no response was received
          console.error('Request data:', error.request);
        } else {
          // Something happened in setting up the request that triggered an Error
          console.error('Error message:', error.message);
        }

        alert('Failed to save playlist.');
      }
    } else {
      alert("Please enter a playlist name.");
    }
  };

  return (
    <div className="App">
      <header>
        <h1>JAMMMING</h1>
        <h3>Spotify Playlist Maker</h3>
      </header>
      <main>
        <SearchResults 
          searchQuery={searchQuery}
          handleInputChange={handleInputChange}
          filteredSongs={filteredSongs}
          handleSearch={handleSearch}
          onAdd={addTrackToPlaylist}
           />
        <Playlist 
          playlistName={playlistName}
          handleChange={handleChange}
          playlist={playlist}
          onRemove={removeTrackFromPlaylist}
          handleSavePlaylist={handleSavePlaylist}
        />
      </main>
    </div>
  );
}

export default App;

Code for SpotifyAuth Component

const clientId = 'MY_CLIENT_ID';
const redirectUri = 'http://localhost:3000';
const scopes = [
    'playlist-modify-public',
    'playlist-modify-private'
];

const getTokenFromUrl = () => {
    const params = new URLSearchParams(window.location.hash.replace('#', ''));
    const accessToken = params.get('access_token');
    const expiresIn = params.get('expires_in');
    return { accessToken, expiresIn };
};

const SpotifyAuth = {
    getAccessToken: () => {
        const tokenData = getTokenFromUrl();
        if (tokenData.accessToken) {
            const expirationTime = new Date().getTime() + (tokenData.expiresIn * 1000);
            localStorage.setItem('spotify_access_token', tokenData.accessToken);
            localStorage.setItem('spotify_token_expiration', expirationTime);
            // Clear URL parameters
            window.history.pushState({}, null, '/');
            return tokenData.accessToken;
        }

        const accessToken = localStorage.getItem('spotify_access_token');
        const expirationTime = localStorage.getItem('spotify_token_expiration');
        if (accessToken && new Date().getTime() < expirationTime) {
            return accessToken;
        } else {
            SpotifyAuth.redirectForAuth();
        }
    },

    redirectForAuth: () => {
        const authUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${encodeURIComponent(scopes.join(' '))}`;
        window.location.href = authUrl;
    },

    makeRequest: async (url, options = {}) => {
        const accessToken = SpotifyAuth.getAccessToken();
        if (!accessToken) {
            throw new Error('Access token not found');
        }

        const headers = {
            ...options.headers,
            Authorization: `Bearer ${accessToken}`,
            'Content-Type': 'application/json'
        };

        try {
            const response = await fetch(url, { ...options, headers });
            if (!response.ok) {
                const errorResponse = await response.json();
                console.error('Error response from Spotify API:', errorResponse);
                throw new Error('Spotify API request failed' + errorResponse.error.message);
            }

            return response.json();
        } catch (error) {
            console.error('Error making request to Spotify API:', error);
            throw error;
        }
    }
};

export default SpotifyAuth;

Troubleshooting Steps Taken:

Error Handling:

Added try-catch blocks around the API requests to capture and log any errors.
Implemented error messages to display to the user when something goes wrong.

DevTools Inspection:

Used Chrome DevTools to inspect network requests and ensure that they are being sent correctly.
Verified that the access token is being retrieved and included in the request headers.

What Actually Resulted

Saving the Playlist:

When trying to save the playlist, the following errors are logged in the console:

Error making request to Spotify API

Error saving playlist

Failed to fetch

The playlist is not being saved to the user’s Spotify account.
The errors suggest an issue with making the API requests, but the specific cause is unclear. Possible issues could be with token management, request headers, or the structure of the API requests.

Despite these efforts, the errors still persist, and the playlist is not being saved to the user’s Spotify account. Any guidance on diagnosing and fixing these issues would be greatly appreciated!

New contributor

Ailee Chang is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật