Help Wizard

Step 1

NEXT STEP

FAQs

Please see below the most popular frequently asked questions.

Loading article...

Loading faqs...

VIEW ALL

Ongoing Issues

Please see below the current ongoing issues which are under investigation.

Loading issue...

Loading ongoing issues...

VIEW ALL

401 Error in API Call.

401 Error in API Call.

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
2 Replies

If any other novices else end up here, I solved the problem like this. The API request was being made before the accessToken had been set, so I separated the useEffect (among other things) to ensure the API call wouldn't trigger before accessToken was set. I'll probably consolidate some but the code below works:

 

 

//Fetch data from the Spotify Endpoint
const getUserData = async (token) => {
const settings = {
headers: {'Authorization': 'Bearer ' + token}
}
const response = await fetch('https://api.spotify.com/v1/me', settings);
const data = await response.json()
return data;
}

const App = () => {
const [showNavPanel, setShowNavPanel] = useState(false)
const closeNavPanel = () => {setShowNavPanel(false)}

const [user, setUser] = useState();
const [accessToken, setaccessToken] = useState(null);
const [refreshToken, setrefreshToken] = useState(null);

//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;
}, {});
//Set accessToken and refreshToken from URL returned from Server Auth
useEffect(() => {
setaccessToken(hashparam.access_token);
setrefreshToken(hashparam.refresh_token);
}, []);

// Get User data from Spotify endpoint once accessToken is set.
useEffect(() => {
async function fetchData() {
if(accessToken != null) {
setUser(await getUserData(accessToken));
}
}
fetchData();
}, [accessToken]);

 

You have helped me so much!!! I had a very similar problem, and reading this clarified the issue for me, Thank you!!

Suggested posts