I'm setting state inside promise all and calling a function but inside the function state still shows empty
Promise.all(fileObjs).then((res) => {
setTradeFilesToUpload(res);
uploadFiles();
});
In Upload function tradefiles shows empty
I'm setting state inside promise all and calling a function but inside the function state still shows empty
Promise.all(fileObjs).then((res) => {
setTradeFilesToUpload(res);
uploadFiles();
});
In Upload function tradefiles shows empty
Setting the state in React acts like an async function.
Meaning that the when you set the state and try to perform an action that's dependant on that state's value right after it, it will likely run before the state has actually finished updating.
Which is why we have useEffect
, a built-in React hook that activates a callback when one of it's dependencies have changed.
Example:
useEffect(() => {
uploadFiles()
// Whatever else we want to do after the state has been updated.
}, [tradeFilesToUpload])
The uploadFiles()
method will run only after the state has finished changing and a render has occurred.
Check the documentation for more info about this.