I got a weird error while working on my Spotify Web Application. I try to save a playlist to my account, which has to fetch the id
element from the https://api.spotify.com/v1/me endpoint, then apply the playlist to your account. Everything seems fine otherwise, besided the fetch to that endpoint, which throws the error:
Spotify.js:81 Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)'
I've never seen this error before, and am not sure why it's happening. The findUserId
method is:
findUserId() {
if(accessToken === undefined) {
this.getAccessToken();
}
console.log(accessToken);
let userId;
fetch(`https://api.spotify.com/v1/me`, {headers: `Bearer ${accessToken}`}
).then(response => {return response.json()}
).then(jsonResponse => {
userId = jsonResponse.id;
});
console.log(userId);
return userId;
}
headers
should be an object - change
{headers: `Bearer ${accessToken}`}
to
{headers: {'Authorization': `Bearer ${accessToken}`}}
First, you have to set the Authentication
header inside headers
. Also, fetch
is async, which means that you try to log userId
before the network request has finished. To fix that, put your log inside the second then
callback and return the fetch
:
findUserId() {
if (accessToken === undefined) {
this.getAccessToken();
}
console.log(accessToken);
return fetch(`https://api.spotify.com/v1/me`, {
headers: { Authentication: `Bearer ${accessToken}` }
})
.then(response => response.json())
.then(jsonResponse => {
userId = jsonResponse.id;
console.log(userId);
return userId;
});
}
Then you can use findUserId
like this:
async otherFunction() {
const userId = await this.findUserId();
console.log(userId);
}
or like this:
otherFunction() {
this.findUserId().then(userId => console.log(userId));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With