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

292
Visualizações
Why's my response being executed more than once with the correct data instead of just only once with useEffect()?

I know having an empty dependency [] executes useEffect() only once but when it does execute only once with an empty dependency [] - it logs an empty array in the console.

When it's not empty, it just continuously logs with no end in sight (with the correct data). I'm not sure why it won't log it correctly just one time with the data I need to use.

What am I doing wrong?

Code below:

const [uploadsData, setUploadsData] = useState([]);

const getUploads = async () => {
    const headers = {
        "Accept": 'application/json',
        "Authorization": `Bearer ${authToken}`
    }

    await axios.get('http://localhost:8000/api/get-uploads', {headers})
        .then(resp => {
            console.log(resp);
            setUploadsData([resp.data]);
        }).catch(error => {
        console.log(error);
    });
};

useEffect(() => {
    getUploads();
    // logs empty array in the console if dependency array is empty
    // logs correct data when dependency array isn't empty - i.e. [uploadsData]
    console.log(uploadsData);
}, []);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

That's because you are referring the uploadsData inside the useEffect hook's callback and in order to get correct console log, you should run that code in a separate useEffect hook.

useEffect(() => {
    getUploads();
}, []);

useEffect(() => {
    // logs empty array in the console if dependency array is empty
    // logs correct data when dependency array isn't empty - i.e. [uploadsData]
    console.log(uploadsData);
}, [uploadsData]);

In this way, the getUploads function is called only once and it outputs correct uploadData to the browser console.

about 4 years ago · Juan Pablo Isaza Relatório

0

The first time it will print empty array since update state is async in React.

GIVEN that you add uploadsData to your dependency array. WHEN your effect runs, it updates uploadsData THEN the effect will be triggered again.

This will go on forever!

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