401 Error in API Call.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
I'm a design trying to learn to code through the Spotify API. I'm having a heck of a time getting my access_tokens saved to state and wondering if anyone has any advice. The code below will return a 401 but when I console.log(accessToken) it appears to be correct. Am I missing a syntax error here or something obvious?
const [user, setUser] = useState();
const [accessToken, setaccessToken] = useState();
const [refreshToken, setrefreshToken] = useState();
useEffect(() => {
extractTokens();
spotifyAuth();
}, []);
//Parse URL sring to get the access token from Spotify
const hashparam = window.location.hash
.substring(1)
.split("&")
.reduce(function(initial, item) {
if (item) {
var parts = item.split("=");
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
//Extract access_token from hashparam
const extractTokens = () => {
setaccessToken(hashparam.access_token);
setrefreshToken(hashparam.refresh_token);
}
console.log(accessToken);
//Fetch data from the Spotify Endpoint
const spotifyAuth = async () => {
const settings = {
headers: {'Authorization': 'Bearer ' + accessToken}
}
const response = await fetch('https://api.spotify.com/v1/me', settings);
const data = await response.json();
setUser(data);
}
Reply
Topic Options
- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page