0

The 'useEffect' function is being used to retrieve data and then store it in the 'ratings' array. I'm currently trying to loop through the 'ratings' array elements in order to console log their contents. This works when the component is first mounted but stops working once the page is refreshed. I found that I can get it to work by placing the 'forEach' outside the useEffect function but was wondering why it doesn't work inside the function and if there's another solution.

const Rating = ({id}) => {
    let url=`https://api.jikan.moe/v3/anime/${id}/stats`;

    const [ratings, setRatings] = useState([]);

    useEffect(() =>
    {
        (async function()
        {

            try{
                const res = await axios.get(url);
                setRatings(Object.values(res.data.scores));

                if (ratings) ratings.forEach((rating)=>{console.log(rating.votes)}); //Doesn't work after refresh
            }
            catch(err)
            {
                console.log(err);
            }

        })();
    }, [url])

...

}

export default Rating;
Hasnat123
  • 45
  • 7

1 Answers1

1

When you do setRatings(Object.values(res.data.scores));, the ratings state is not updated imediatelly, so if (ratings) is still the empty array when the app runs if (ratings) ....

Do something like this instead:

  const scores = Object.values(res.data.scores);
  setRatings(scores);
  if (scores) scores.forEach((rating)=>{console.log(rating.votes)});

or use another useEffect for the ratings so it runs when it gets updated:

useEffect(() => {
  if (ratings) ratings.forEach((rating)=>{console.log(rating.votes)});
}, [ratings]);
arieljuod
  • 15,460
  • 2
  • 25
  • 36
  • I understand the second solution but am unsure why the first solution would work. Even if you store the data into another variable (i.e. scores), would it also not be updated immediately, meaning that the `ratings` array is still empty and thus return an error? – Hasnat123 Dec 10 '21 at 15:02
  • 1
    for the first solution it's not using the `ratings` state, it's using the local `scores` variable, that does have the correct values at that moment – arieljuod Dec 10 '21 at 22:18
  • I understand now thank you :) – Hasnat123 Dec 13 '21 at 02:50