0

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

Ivan Reshetnikov
  • 398
  • 2
  • 12
Maheskumar
  • 161
  • 1
  • 11
  • why not use another `then` after you're setting your state and there you call your function – buzz Aug 23 '22 at 08:42
  • 1
    If you're expecting `setTradeFilesToUpload` to change the corresponding local variable (`tradeFilesToUpload`, i'm guessing), it won't. Calling `setTradeFilesToUpload` just asks react to re-render the component. That new render will have its own local variables, but your code from the previous render cannot access them. Why not pass `res` into uploadFiles? – Nicholas Tower Aug 23 '22 at 08:43

1 Answers1

3

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.

  • Note: "tradeFilesToUpload" in the example is interchangeable with whatever other state piece you're dealing with.

Check the documentation for more info about this.

tomleb
  • 2,409
  • 2
  • 9
  • 24
  • **Note:** this is based on the assumption that your original issue was that `uploadFiles()` at some point uses the value of `tradeFilesToUpload` and therefor gets the previous state value. – tomleb Aug 23 '22 at 08:47