Search code examples
reactjsreduxstore

On props (store) change Do


I have a store Object (React-Redux App using connect to interact with my JAVA API) called parameters.

this object is updated in another component when I update inputs tick boxes ect...

In my new Component I have a "Save as Template" button which sends this Object after some processing as a Json to my API.

I'd like to now CATCH changes to this Object (parameters) within my new component with any odd function.

So that I may run a series of "if" tests on it, see if some inputs are missing and hide or grey out the "Save as template" button correspondingly.

Is that possible?

componentDidMount() {

}

and

componentWillReceiveProps() {

}

don't seem to be of much help.


Solution

  • Yea this is a pattern I've had to use a few times, and I used lodash.isEqual to handle it.

    import { isEqual as _isEqual } from "lodash"
    

    Say you have a parameters object in you store and you're watching it in your component in mapStateToProps for example (or however else you're getting access to it):

    const mapStateToProps = (state) => ({
        parameters: state.someApp.parameters,
    });
    

    You can then check if anything has changed in your componentWillReceiveProps:

    componentWillReceiveProps(nextProps) {
        if(!_isEqual(this.props.parameters, nextProps.parameters)) {
          this.props.sendSomeRequestWithParameters(nextProps.parameters)
        }
    }