'trigger a function on state change when condition is met
I have initial state null in redux store but i want to trigger a function when that state is populated with a promise response if it met a condition in state.
this is my state in redux.
const Initial_state = {
orderStatus: null,
}
when promise resolve state is updated like this
orderStatus={status:200,message:'order place"}
i want to run a function in my component whenever state is changed and only if status is 200.
But if i use if statement it returns error as status does not exits in state initially
Solution 1:[1]
if i well understand your question you should use the useEffect hook. Here is the documentation https://reactjs.org/docs/hooks-reference.html#useeffect.
So finally in your component you should have something like this :
useEffect(() => {
if (orderStatus?.status === 200) {
// Do something when status is 200
}
}, [orderStatus]);
I also want to suggest to define an empty object rather than null for you default value on the redux store :
const Initial_state = {
orderStatus: {},
}
Hoping my answer can help you in your search.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jerome gallego |
