Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading