Home > OS >  How to rerun-useEffect() after dispatching an redux action in react native?
How to rerun-useEffect() after dispatching an redux action in react native?

Time:12-02

I'm working on react native application with redux, The reducer looks something like this,

    reducer = {
      dataA: {},
      dataB: {},
      laoding: false,
      error: false
    }

I have created a redux action which will update dataA object in reducer. I called the action from one of my react-native components in useEffect().

useEffect(() => {
 dispatch(dataA())
}, [])

I haven't passed any dependency array.

Everything works great, But from the same component where I explicitly dispatching an action to update dataB object which will incur update the dataA from the backend itself.

I'm expecting that, whenever i dispatch an action explicitly to update the dataB, the useEffect
should re-run to get the latest updated object values from dataA object.

But it is not happening, Even I try to pass dataA object as dependency to useEffect, it going an infinite loop of useEffect.

And also, dataB object consists boolean value which i want to display alert box when ever i dispatch an action to update dataB.

  dataB = {
   result: {
     success: true || false,
     Message: "Something"
    }
  }

thanks in advance

CodePudding user response:

I hope this helps you. you can try this :

 useEffect(() => {
    dispatch(dataA())
}, [dataB])
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

It goes to infinite loop because you update dataA and give dependency dataA which calls this useEffect again and again. You could give dataB as dependency and this means whenever dataB changes call this useEffect.

  • Related