Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
Console log inside React 'useEffect' function doesn't work after page refresh

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;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda