Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

263
Views
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 answers
Answer question

0

Run an effect whenever state data changes

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

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!