0
votes

What I'm trying to achieve: user clicks a button on a React page, is redirected to Spotify to authorize, comes back to my page and my app receives an access token.

I figured that I need to use the implicit grant flow from their authorization docs. I'm using jQuery to send a GET request:

$.ajax({
  url: urlToFetch,
  type: 'GET',
  success: data => {
    // what do I put here?
  }
})

I can't figure out what to put in the success function, to redirect the user to their login page and then redirect them back with an access token?

Sorry if this is a silly question - I'm a beginner but I just can't figure it out.

1
Is there a reason you aren't doing the request in React? - Colin Ricardo
@Colin I've tried the below if that's what you're referring to: fetch(urlToFetch).then(response => { }, 'json') - but I still don't know what to put inside the curly brackets. My problem is I don't understand what function to write to redirect the user to the login page and back. - ilmoi
You should look into something like react-router. Alternatively, you can do window.location.href = '/whatever'; to navigate to a URL. - Colin Ricardo

1 Answers

1
votes

If all you need to do is redirect the user to the login page, you can do this simply setting the value of window.location.

See this example here:

var url = 'https://accounts.spotify.com/authorize';
url += '?response_type=token';
url += '&client_id=' + encodeURIComponent(client_id);
url += '&scope=' + encodeURIComponent(scope);
url += '&redirect_uri=' + encodeURIComponent(redirect_uri);
url += '&state=' + encodeURIComponent(state);

window.location = url;

This may not be enough for what you need, so you may want to check out this tutorial:

https://medium.com/@jonnykalambay/now-playing-using-spotifys-awesome-api-with-react-7db8173a7b13