I’m trying to add Spotify’s new browser playback feature to my React app. But I’m stuck. Here’s what I want to do:
- User clicks a login button
- After successful login, I get an access token
- Then I load the Spotify script
- Finally, I set up the player with the token
The problem is the Spotify object isn’t there when my code runs. It only shows up after the script loads. How can I fix this?
Here’s a bit of my code:
import ScriptLoader from 'react-script-loader'
function handleScriptReady() {
const myToken = this.props.userTokens.accessKey
const musicPlayer = new Spotify.Player({
playerName: 'My Cool Music App',
getAuth: callback => { callback(myToken) }
})
musicPlayer.start()
}
// In the render part:
<ScriptLoader
scriptUrl='https://player.spotify.com/sdk.js'
onScriptFail={this.handleScriptFail}
onScriptSuccess={this.handleScriptReady}
/>
Any ideas on how to make this work? Thanks!
I’ve faced a similar issue when integrating Spotify’s SDK into a React app. One effective solution is to verify that the Spotify object exists before initializing your player. For example, in your handleScriptReady function, instead of directly creating the player, you can set up a polling mechanism using setInterval to check if window.Spotify is defined. Once it is, clear the interval and proceed with initializing the player (e.g., calling initializePlayer). This ensures that the Spotify object is loaded and available, preventing errors when you create a new Spotify.Player instance.
I’ve been down this road before, and it can be tricky. One approach that worked for me was using a custom hook to manage the Spotify SDK loading and initialization. Here’s a rough idea: create a useSpotifySDK hook that handles script loading and player setup. Inside this hook, use useState to track the SDK’s ready state and useEffect to load the script dynamically. Once the script is loaded, you can initialize the player within the same useEffect, ensuring that the Spotify object exists before trying to use it. This helps keep your main component clean while encapsulating all the SDK-related logic. It’s been a pretty reliable method in my experience.
hey emmat83, ive dealt w/ this before. try using a useEffect hook to load the script dynamically. something like:
useEffect(() => {
const script = document.createElement(‘script’);
script.src = ‘https://player.spotify.com/sdk.js’;
script.async = true;
script.onload = () => {
// init player here
};
document.body.appendChild(script);
}, );