Search code examples
reactjsuse-effectuse-state

What's the better way to change state on every render for number of times


Using useEffect I am calling some data from different URLs through axios and trying to change the URL on every render, I am using a state to change URL and whenever the state changes, the URL will also change and run the useeffect again with different URL. But to change the state in the render I am using a button, My question is there any ways to make the state change and run the API call without the button click.

import React,{useState,useEffect} from "react";
import axios from "axios";


export default function TrackLoader(accessToken){

    const [number, setNumber] = useState(0);
    const [arrayOfPlayLists, setArrayOfPlayLists] = useState([]);

    const playListIds = ["3d93aG1WkqLxS2q9GkUgXO", "37i9dQZF1DWX3xqQKu0Sgn", "37i9dQZF1DWU13kKnk03AP", "37i9dQZF1DXdPec7aLTmlC", "37i9dQZF1DX889U0CL85jj", "37i9dQZF1DXbVipT9CLvYD"]
    
    useEffect(() =>{
        async function getData(){
            
            const response = await axios.get(`https://api.spotify.com/v1/playlists/${playListIds[number]}`,{
                headers:{
                    Authorization:"Bearer " + accessToken.accessToken,
                },
            })
            let selectedPlayList = response.data
            setplayList(selectedPlayList)
            arrayOfPlayLists.push(selectedPlayList)
        }
        getData();
    },[number]);

    return(
        <div>
            {number ===5? null: <button onClick={()=> setNumber(number+1)}></button>} 
        </div>
    )


}



And also additionally I am trying to put the data I got from API in an array. Sorry for my English.


Solution

  • You can add another useEffect with setTimeout

      useEffect(() => {
        if(number <= 5) {
          setTimeout(() => {
              setNumber(number + 1);
            }, 1000);
        }
      }, [number]);