Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

265
Vistas
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 Respuestas
Responde la pregunta

0

Run an effect whenever state data changes

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

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda