I'm making an app in React using Spotify API.
First, I get the access token using my clientID and clientSecret. Then I'm trying to get the userID using this token. The documentation mentions that you need to make a get request and pass the token as a header.
The problem is, I always get a 401 error code in response. The documentation mentions that this error may be because the token has expired. But in my code I am trying to get the userID immediately after getting the token.
My second question is about making requests in React. As you can see, I used the useEffect hook to achieve this, but I'm not sure if this is the correct approach. Also, the way I'm doing the second request doesn't feel right (if statement inside useEffect).
Any help is greatly appreciated!
P.S. apiKey and apiSecret are global variables, the first request worked fine, it returned a valid token, which was successfully used to make another get request to search for songs.
const [token, setToken] = useState(""); const [userID, setUserID] = useState(""); // Obtain access token and user ID useEffect(() => { // Get access token const parameters = { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: `grant_type=client_credentials&client_id=${apiKey}&client_secret=${apiSecret}`, }; fetch("https://accounts.spotify.com/api/token", parameters) .then((response) => { return response.json(); }) .then((data) => { setToken(data.access_token); return data.access_token; }); }, []); // Obtain user ID once token is obtained useEffect(() => { if (token != "") { const parameters = { method: "GET", headers: { Authorization: `Bearer ${token}`, }, }; fetch("https://api.spotify.com/v1/me", parameters) .then((response) => { return response.json(); }) .then((data) => { console.log(data); }); } }, [token]);
It looks like your code is on the right track, but the problem may have to do with how the token is handled and when the second request for the user ID is made. Furthermore, there is no need to use two
useEffect
hooks.