Home > Software design >  How to use a callback to a setState or something similar
How to use a callback to a setState or something similar

Time:12-25

So this is the code I have been working on, it gets the data from API, then I assign the data to slides (using setSlides). After that I need to create a new array without the first one, but apparently slides is still null when it executes the setInterval. Which sounds not okay since then is only executed when the request is sucessful. Can anyone tell me what's wrong.

 //---getting data from api
    useEffect(() => {
        axios
            .get(DATA_URL, headers)
            .then((answer) => {
                setSlides(answer.data.spotlights);

                let newArr = [...slides];
                newArr.shift();
                setTrio(newArr);
                setSpolight(answer.data.spotlights[0]);
                const interval = setInterval(() => {
                    switchSpolight();
                }, 4000);
                return () => clearInterval(interval);
            })
            .catch((answer) => console.log(answer));
    }, []);

CodePudding user response:

I thing the problem is that you are trying to access the slides state right after the setSlides "which will not be available at that moment"

so I suggest you try this instead

before:

setSlides(answer.data.spotlights);
let newArr = [...slides];

after:

setSlides(answer.data.spotlights);
let newArr = [...answer.data.spotlights];

CodePudding user response:

The solution to this problem is to move the code that relies on the updated value of slides into a separate function, and call that function inside the then block, after the setSlides function has been called.

For example:

useEffect(() => {
  axios
    .get(DATA_URL, headers)
    .then((answer) => {
      setSlides(answer.data.spotlights);

      function updateTrio() {
        let newArr = [...slides];
        newArr.shift();
        setTrio(newArr);
        setSpolight(answer.data.spotlights[0]);
        const interval = setInterval(() => {
          switchSpolight();
        }, 4000);
        return () => clearInterval(interval);
      }

      updateTrio();
    })
    .catch((answer) => console.log(answer));
}, []);
  • Related