Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen for specific property changes in Redux store after an action is dispatched

I am currently trying to conceptualize how to handle dispatching an action in a component based on a data change after a dispatch in another component.

Take this scenario:

dispatch(someAjax) -> property in state updates.

After this, I need another component dependent on this same property to know that is has updated and dispatch an action based on the new value.

Rather than using some type of value.on(change... solution, what is the preferred way to handle this type of action 'cascading'?

like image 914
Jazzy Avatar asked Apr 11 '16 19:04

Jazzy


People also ask

What happens after dispatch Redux?

It's called a middleware. A middleware can intercept any action triggered by a dispatch, also it has access to the store. At the end of your middleware your just use a callback to tell the flow to continue. You need to pass your action to it so your reducers can finally be called and receive the action.

Who is responsible for dispatching the action in Redux?

A Redux app really only has one reducer function: the "root reducer" function that you will pass to createStore later on. That one root reducer function is responsible for handling all of the actions that are dispatched, and calculating what the entire new state result should be every time.


1 Answers

You may use Redux's mapStateToProps and connect with React's componentDidUpdate(prevProps, prevState, snapshot) hook.

So basically your code could look like this:

const mapStateToProps = (state) => ({     specificProperty: state.specificProperty,    // any props you need else });  class YourComponent extends React.Component {     render() {       // render your component       }      componentDidUpdate(prevProps, prevState, snapshot) {         if (prevProps.specificProperty !== this.props.specificProperty) {             // Do whatever you want         }     } }  YourComponent = connect(mapStateToProps)(YourComponent); 
like image 91
PinkiNice Avatar answered Oct 09 '22 13:10

PinkiNice