Home > Back-end >  How to console.log data from an API call in this situation?
How to console.log data from an API call in this situation?

Time:10-30

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)

CodePudding user response:

Run an effect whenever state data changes

useEffect(() => {
  if(data.length) {
    console.log(data)
  }
}, [data])

CodePudding user response:

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

  • Related