Home > Software design >  What is correct way to call function inside setState(useState) hooks
What is correct way to call function inside setState(useState) hooks

Time:11-22

I want to update state at real time and call function inside setState but i am getting error.

onClick={() => setDetails(prevState => ({...prevState,id: product.orderId,status: 'processing'}) => updateStatus() )}

enter image description here

Can someone tell me correct syntax and expression

CodePudding user response:

It seems you are using hooks. You can't call a function in setState like in class components. You need to watch it through useEffect.

React.useEffect(() => {
  updateStatus() 
}, [state.id, state.status])

CodePudding user response:

Provide more detail about your code . For example , provide the component you are writing . So we can understand what is going on . Improve your question .

CodePudding user response:

the function created using useState hook doest have a second argument. it will not support call back function after updating the state. it was only there in the setState function which is used in class components.

You can use useEffect instead

useEffect(()=> {
   updateStatus()
}, [details])

   return (
     ...
    onClick={() => setDetails(prevState => ({...prevState,id: product.orderId,status: 'processing'}))}
     ...
    )

in this way, on every setDetails update it will call useEffect and then updateStatus

  • Related