skip to Main Content

I am trying to poll the spotify API every second with setInterval when the component is loaded in. However, when testing this I receive an error: Invalid Hook Call..etc.
I believe this is because I am using useEffect within another useEffect when I am polling. I am not sure how to overcome this.

const getCurrentSong = () => {

        useEffect(() => {
            fetch('/spotify/current-song').then((response) => {
                // check if not ok
                if(!response.ok){
                    return {};
                } else {
                    return response.json();
                }
            }).then((data) => {
                setSong(data);
                console.log(data);
            });
        },
        [])
        
    }

    getRoomdetails();
    getCurrentSong();
    
    useEffect(() => {
        const interval = setInterval(()=>{
            //getCurrentSong();
            console.log("test");
        }, 1000)

        return () => clearInterval(interval);
    }, []);

This is the part of the code that is of concern. I initially tried to get rid of the useEffect in the getCurrentSong function but this would mean that I would get stuck in a loop of that function running which is not what I want. Ideally, I want the component to render, call the API, then poll it every second for any updates.

2

Answers


  1. You can handle the polling in the first useEffect itself. Please try updating your code as:

    const getCurrentSong = () => {
        fetch('/spotify/current-song')
            .then((response) => {
                if (!response.ok) {
                    return {};
                } else {
                    return response.json();
                }
            })
            .then((data) => {
                setSong(data);
                console.log(data);
            });
    };
    
    
    useEffect(() => {
        getRoomdetails();
        getCurrentSong();
    
        const interval = setInterval(() => {
            getCurrentSong(); 
            console.log("test");
        }, 1000);
    
        return () => clearInterval(interval);
    }, []);
    
    Login or Signup to reply.
  2. UseEffect is designed to run when listening to changes to a state or run once. As your second array param is an empty array it will only run once when rendered.

    My suggestion is to remove the use Effect all together and have getCurrentSong run every second to set the Song state.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search