React Native - how do I trigger a function based off a change in a reducer value?

345 views Asked by At

I have a question about how to trigger a function in one component on the change of a reducer value from a different component.

I currently have a function in my Home component that runs in ComponentDidMount. If my value this.props.reducer.run is true the function fires. The initial state is set to true so the function fires when the app first loads.

In my Profile component I have a toggle switch with toggles this.props.reducer.run to true or false. Is it possible to trigger my function in Home when a change to the reducer value occurs?

Below is a mock up of the code i have, i am wondering if ComponentDidUpdate is what I should be looking at, if so some guidance would be appreciated:

Home.js

...

myFunction() = > {
   console.log('fired')
}

ComponentDidMount() {
   //runs on load
   if(this.props.reducer.run == true) {
     this.myFunction()
   }
}

...


**Profile.js**

...

toggleRun = () => {
   this.props.setRun(!this.props.reducer.run)
}
...
1

There are 1 answers

0
Ethan Lipkind On

yes, you can do this with componentDidUpdate. When componentDidUpdate is invoked, it will be passed the previous value of your component props (let's call this prevProps). By comparing the prevProps.reducer.run to this.props.reducer.run, you can determine if the value changed and, if it did, call your function accordingly.

Alternatively, if this were a functional component you could achieve the same with useEffect.