How to unsubscribe from redux store when component will unmount? How to decorate redux connect?

15,801

Solution 1

connect has a second parameter of ownProps, which is an object containing all passed-in props. You would do something like this:

const mapStateToProps = (state, { reducerName = 'defaultReducer' }) => ({
  some: state[reducerName],
});

export default connect(mapStateToProps)(MyComponent);

Solution 2

To unsubscribe you can simple execute the function return by store.subscribe:

componentDidMount() {
  this.unsubscribe = store.subscribe(() => {
    // ...
  });
}
componentWillUnmount() {
  this.unsubscribe();
}
Share:
15,801

Related videos on Youtube

Nemo Free
Author by

Nemo Free

Updated on June 04, 2022

Comments

  • Nemo Free
    Nemo Free almost 2 years

    I am passing the following props (storeName) to my component:

    <MyComponent reducerName="city" />
    

    and I want to connect to store with a dynamic name (this.props.reducerName)

    for example

    export default connect(state => ({
        some: state[this.props.reducerName]
    }), { })(MyComponent);
    

    How to decorate redux connect, or what i must to do?

    I tried to skip redux connect and used store.subscribe

    componentDidMount() {
        store.subscribe(() => {
            this.setState({some: store.getState([this.props.reducerName]});
        });
    }
    

    But when I move to another page, I see the following error:

    Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.

    How to unsubscribe from redux store when component will unmount?