1

I have the following problem when I request data from the Spotify API, at first I get it, but when I reload the page or try to write this state using useState, an error 400 or 401 occurs. The code I use to get the data: `

import axios from 'axios';

const BASE_URL = 'https://api.spotify.com/v1';

export const fetchFromAPI = async (url: string, token: string) => {

    const { data } = await axios.get((`${BASE_URL}/${url}`), {
        method: 'GET',
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`
        },
    });

    return data;
}

`

Next, I use the fetchFromAPI function:

`

const { token } = useContext(Context);

    const [albums, setAlbums] = useState<string[]>([]);

    useEffect(() => {
        fetchFromAPI('browse/new-releases', token)
            .then((data) => console.log(data));
    }, [token])

`

I've tried logging out of my account and back in, I've also tried other links to get data but it's always the same problem. I also checked if the token is present before requesting the data and it is

1 Answers1

0

Ok, I managed to find and solve this error myself. The error was that I didn't have a user token yet, but useEffect was already starting to receive data.

useEffect(() => {
if (token) {
  fetchNewReleases();
  fetchFeaturedPlaylists();
  fetchCategories();
  fetchRecommendations();
} else {
  console.log('error');
}}, [token])

For example, this piece of code will print an error twice, and only after that I receive a token and can receive data from the API.

To be honest, I didn't know how to run useEffect only when I have a token, so I solved it in a simpler way, but I don't know if it's completely correct, I have the following condition Object.values(state).length) !== 0 and if it is true, only then will I display the data from the API