Problems adding Spotify script with reactJS

Asked

Viewed 40 times

0

I was trying to link the Spotify API script to the React component, but when I use the "window.onSpotifyWebPlaybackSDKReady" function it shows the error:"Property onSpotifyWebPlaybackSDKReady does not exist on type 'Window & typeof globalThis"as if he didn’t recognize the script. How can I fix this ?

import React, { useEffect, useState } from 'react';

function SpotifyPlayer() {

    useEffect(() => {
    const script = document.createElement("script");
    script.src = "https://sdk.scdn.co/spotify-player.js";
    script.async = true;
    document.body.appendChild(script);
    window.onSpotifyWebPlaybackSDKReady = () => {
      // do your spotify magic here.
    }
    }, []);
      
}

export default SpotifyPlayer;

NOTE: the main HTML is in one folder and the component is in another, but I have tried to put the script tag in the main html body and yet it did not recognize the function in the component.

1 answer

0

onSpotifyWebPlaybackSDKReady is not a property of window, and as Typescript tries to keep your code consistent with the declared types, it is not letting you assign a value to a property that it does not know.

But there is not much to do in this case, ideally this module would have to give you a callback that does not need to be exposed in window, however as it works like this, you will have to escape a little from the Typescript methodology to insert this property by force.

One way to do this is by doing a cast of the kind Window for any, which is a dynamic type that accepts any property. So you could write as

(window as any).onSpotifyWebPlaybackSDKReady = () => {
  // do your spotify magic here.
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.