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

264
Visualizações
How to console.log data from an API call in this situation?

In getData() function, I'm console.logging data to see if it set in the state properly after an asynchronous call. It's returning Array[] which I'm guessing means that the data set but console.log is running before the fetch finishes.

The console.log in the useEffect works properly although it will log it twice.

Is there a way to console.log inside of getData() function or is it the proper way to do it in the useEffect?

useEffect console.log runs twice because I'm guessing once after the data is retrieved and set into state, and then after it's set, it console logs it again after the re-render.

const TestComponent = () => {
    // State for Data
    const [data, setData] = useState([])
    // URL for Data
    const url = 'https://randomuser.me/api/?results=20'
    // Retrieve Data - Function
    const getData = async() => {
        const { results } = await (await fetch(url)).json()
        setData(results)
        console.log(data)
    }
    
    useEffect(() => {
        getData()
        console.log(data)
    },[])
return (JSX)
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Run an effect whenever state data changes

useEffect(() => {
  if(data.length) {
    console.log(data)
  }
}, [data])
about 4 years ago · Juan Pablo Isaza Relatório

0

const getData = async() => {
        const { results } = await (await fetch(url)).json()
        setData(results)
        console.log(data)
    }
    
    useEffect(() => {
        getData()
        console.log(data)
    },[])

useEffect only execute once, you are seeing console.log twice simply because one in getData while another in useEffect

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