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.
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
