Search code examples
reactjsspotify

Spotify Webplayback SDK is not defined in ReactJS


So I have a relatively fresh reactjs project setup where my parent component is trying to initialize the spotify webplayback SDK. The only problem im facing here is that everytieme I try to initialize the SDK with the Spotify class it complains that Spotify is undefined.

Now the way the docs on https://developer.spotify.com/documentation/web-playback-sdk/reference/#initializing-the-sdk described it was that I needed to immediately define window.onSpotifyWebPlaybackSDKReady after I call their SDK, so this is what my return html looks like:

return (
        <div>
            REEEEEE
            <script src='https://sdk.scdn.co/spotify-player.js' onLoad={handleScriptLoad()}></script>
            <script>
                window.onSpotifyWebPlaybackSDKReady = () = {">"} {
                    handleInit()
                };
            </script>
        </div>
    );

This seems to work fine and even manages to call the specified handleInit method, but the moment I try to add the Spotify reference it complains. All examples I find online seem to just call it without any reference from what I see. Any idea how this is meant to work in ReactJS?

Working function:

function handleInit() 
    {
        console.log('awwwww man');
      
    }

Non working function:

function handleInit() 
    {
        console.log('awwwww man');
        const token = props.token;
        const player = new Spotify.Player({
                name: 'Web Playback SDK Quick Start Player',
                getOAuthToken: cb => { cb(token); },
                volume: 0.5
        });

        player.connect();
    }

Solution

  • You will want to add the following line to index.html instead of a component.

    <script src="https://sdk.scdn.co/spotify-player.js"></script>
    

    Now, in your React app you can write a hook that tells if it is ready, and consume the hook and the SDK wherever you need in your code:

    const useIsSpotifyReady = ()=>{
     const [isReady, setIsReady = useState(false)
    
     useEffect()=>{
      window.onSpotifyWebPlaybackSDKReady = () => {
        setReady(true)
      };
     }
     
     return isReady
    }
    

    Another alternative is to use a react-spotify-web-playback-sdk which they already provide a solution for it:

    mport { WebPlaybackSDK } from "react-spotify-web-playback-sdk";
    
    const AUTH_TOKEN = "your token here!";
    
    const MySpotifyPlayer: React.VFC = () => {
      const getOAuthToken = useCallback(callback => callback(AUTH_TOKEN), []);
    
      return (
        <WebPlaybackSDK
          deviceName="My awesome Spotify app"
          getOAuthToken={getOAuthToken}
          volume={0.5}>
          {/* `TogglePlay` and `SongTitle` will be defined later. */}
          <TogglePlay />
          <SongTitle />
        </WebPlaybackSDK>
      );
    };