-1

I'm quite new to hooks and in react in general. I came accross a problem I couldn't solve so here it is. I have a quotation function that is suppose to calculate the cost price of a benefit.

const quotation = useCallback(()=> {
  setCostPrice(0)
  keys.forEach(e => {
    for (const property in values){
      if ((property==e && values[property]==true){
        setCostPrice(costPrice + pricing[property])
      }
    }
  })
})

Here is my problem, i'm calling the function quotation() everytime a checkbox is checked (so the cost price will update). The problem is, the function is suppose to "reset" the costprice at 0 everytime it is called but since using "setCostPrice(0)" is asynchronous the result is not the right one. I've read different post concerning using useEffect() but when i'm using useEffect the function can't read the value from values[property].

I don't know how I can fix this issue if anyone wants to help I would appreciate !

Neriss
  • 1
  • 1

1 Answers1

-1

If you need to wait for some asynchronous actions, just make your function async and use await inside:

const quotation = useCallback(async ()=> {
  await setCostPrice(0)

  ...
})

Or use .then() if you're not able to apply async/await:

const quotation = useCallback(()=> {
  setCostPrice(0).then(() => {
    keys.forEach(e => {
      ...
    });
  });
})

If this setCostPrice() comes from useState() hook like that:

const [ , setCostPrice ] = useState(...);

You can just provide callback there to receive latest state;

setCostPrice(
  oldPrice => { /* return new price from here */ }
);

By the way, you need to provide list of deps for useCallback() hook. Otherwise it won't work.

Andres
  • 967
  • 6
  • 7
  • These state setters don't return a Promise, so `async/await` and `then` won't work like you want them to. – Emile Bergeron Dec 10 '19 at 16:58
  • Just tried and indead it's not working :/ – Neriss Dec 10 '19 at 17:00
  • I've seen only statement that `setCostPrice(0)" is asynchronous the result is not the right one` and didn't expect it comes from `useState()` hook. See my updated answer. – Andres Dec 10 '19 at 17:04