Home > database >  How to add call back when 2 state update at the same time using hooks?
How to add call back when 2 state update at the same time using hooks?

Time:09-30

How to add call back when more than 2 states update at the same time. please check bellow code of class component where I add a call back when that states will updated successfully.

this.setState({liveMatches: finalMatches, isLoading: false, runningFetch: false, disbleSportsSwitch:false}, ()=> this.startListener());

But Now I What to convert this code in hooks inside the functional component.

Useeffect(()=>{
  startListener());
},[liveMatches,isLoading,runningFetch,disbleSportsSwitch])

Please check is it correct or not ?

CodePudding user response:

The closest to what you have in the class setup would be:

const [liveMatches, setLiveMatches] = useState(/* default value */);
const [isLoading, setIsLoading] = useState(/* default value */);
const [runningFetch, setRunningFetch] = useState(/* default value */);
const [disbleSportsSwitch, setDisbleSportsSwitch] = useState(/* default value */);

// later
const onSomeEvent = () => {
  setLiveMatches(finalMatches);
  setIsLoading(false);
  setRunningFetch(false);
  setDisbleSportsSwitch(false);
  this.startListener();
};

onSomeEvent depends on the context of your app. It might be page load or a button click. Its not possible to say from your question

If those 4x pieces of state are closely related (liveMatches, isLoading, etc) you could also consider useReducer - but I would start with useState until you comfortable with hooks (or if it becomes too complex)

CodePudding user response:

The code you provided above will add a callback on every state change.(please provide dependency array correctly)

But you can identify the dependecy causing effect by introducing your custom hook and if 2 or more than 2 found changed then add your callBack

  • Related