Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React async data fetch in useEffect

I'm trying to load data through an asynchronous method in useEffect. I pass all the necessary dependencies and, in my understanding, useEffect should work when the component is mounted, on the first render, and when dependencies change.

useEffect(() => { 
        console.log('effect')
        if (ids.length === 0) {
            api.images.all().then((data) => { console.log(data); setIDs(data) }).catch(console.log)
        }
    }, [ids])

In my case it's 3 times: mount (it should load data immediately), first render (shouldn't go into if), and due to ids change (should also not go into if). But useEffect fires 4 times and loads data twice, I can't figure out why.

enter image description here

Component code:

//BuildIn
import { useEffect, useState } from 'react'
//Inside
import api from '../services/api.service'
import AsyncImage from '../components/AsyncImage.component'

const ImagesPage = () => {
    const [ids, setIDs] = useState([])

    useEffect(() => { 
        console.log('effect')
        if (ids.length === 0) {
            api.images.all().then((data) => { console.log(data); setIDs(data) }).catch(console.log)
        }
    }, [ids])

    return(
        <>
            {(ids.length > 0) ? ids.map((id, index) => <AsyncImage guid={id} key={index} />) : <div>No data</div>}
        </>
    )
}

export default ImagesPage
like image 634
Pedro Avatar asked Nov 01 '25 11:11

Pedro


1 Answers

I've re-implemented the business logic of your example and it works well. The only thing you have to fix is to pass the setIDs to the useEffect as a dependency. The component renders twice which is fine; the first one is the initial render and the second one occurs when the data is present.

You can even get rid of the if condition. Simply do not pass the id to the useEffect hook and it will fetch the images on mount only.

// import { useState, useEffect } from 'react' --> with babel import
const { useState, useEffect } = React  // --> with inline script tag

const api = {
  images: { all: () => new Promise(res => res(['id1', 'id2'])) }
}

const ImagesPage = () => {
    const [ids, setIDs] = useState([])

    useEffect(() => { 
      api.images.all()
      .then(data => {
        setIDs(data)
      })
      .catch(console.log)
    }, [setIDs])

    return(
      <ul>
        {console.log('reders')}
        {ids.map(id => <li key={id}>{id}</li>)}
      </ul>
    )
}

ReactDOM.render(<ImagesPage />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
like image 194
gazdagergo Avatar answered Nov 04 '25 03:11

gazdagergo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!