'ReactJs state inside of nested function is not being updated, but it is updated outside(in fucntional component)
I'm trying to send get requests at certain interval using setInterval. So my script looks like that:
const [package_id, setPackageId] = useState({id: 1, result: NaN})
async function get_images(detail_id){
axios.get('http://127.0.0.1:8000/get_images', {params: {detail_id}, headers:{
'Cache-Control': 'no-cache',
'Pragma': 'no-cache',
'Expires': '0',
}}).then((res) =>{
... // some processing
setPackageId(prevstate => {return {...prevstate, id :prevstate.id + 1}})
}
).catch(errs => {
console.log(errs)
})
}
useEffect(() => {
const request_interval = setInterval(get_images, 2000, package_id.id)
return () => clearInterval(request_interval);
}, [])
Even though state package_id.id is being updated(I checked using useEffect). In get_images function, it's value is always the same. How can I use updated value of state?
PS: I also tried to access state inside of function(without passing argument (detail_id)), but it didn't work either.
Any help would be appreciated.
Solution 1:[1]
I think you want to pass package_id.id through setInterval
But you didn't add package_id.id as a dependency in the useEffect
so you're passing the same id every time
because the effect here doesn't listen to the id updates
But if you add package_id.id as a dependency
the effect will keep listening for id updates and the effect will keep getting triggered
So you can try this
I hope this will help you
const [package_id, setPackageId] = useState({id: 1, result: NaN})
const get_images = useCallback(async () =>{
axios.get('http://127.0.0.1:8000/get_images', {params: {package_id.id}, headers:{
'Cache-Control': 'no-cache',
'Pragma': 'no-cache',
'Expires': '0',
}}).then((res) =>{
... // some processing
setPackageId(prevstate => ({...prevstate, id :prevstate.id + 1}))
}).catch(errs => {
console.log(errs)
})
}, [package_id])
useEffect(() => {
const request_interval = setInterval(get_images, 2000)
return () => clearInterval(request_interval);
}, [get_images])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AmelloAster |
