How to reuse a Redux store from inside a React library

Viewed 824

I have two repositories split up like this:

main-app: A create-react-app project defining a redux store with some reducers.

const reducers = combineReducers({
    reducer1: myReducer
});
const store = createStore(reducers);
const app = (
    <Provider store={store}>
        <App />
    </Provider>
);
ReactDOM.render(app, document.getElementById('root'));

And an App component returning <AppHeader /> in the render method defined below, in my lib-header library.

lib-header: An external library using the main app's store, defined like this:

class AppHeader extends Component {
  render() {    
    return (
        <div>{this.props.isAuthenticated ? 'User authenticated' : 'User not authenticated'}</div>
    );
  }
}

AppHeader.propTypes = {
    isAuthenticated: PropTypes.bool,
    onSignin: PropTypes.func
};

const mapStateToProps = state => {
    return {
        isAuthenticated: state.auth.token !== null
    }
};

const mapDispatchToProps = dispatch => {
    return {
        onSignin: () => dispatch(actions.signIn())
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(AppHeader);

However, when lib-header tries to use the connect(...) function, it generates this error:

Could not find "store" in the context of "Connect(e)". Either wrap the root component in a , or pass a custom React context provider to and the corresponding React context consumer to Connect(e) in connect options.

For some reasons, the store defined in the Provider of the main app does not get through to the external library, even though the AppHeader component is defined inside the Provider component of my main app.

Any help would be appreciated.

Thanks!

0 Answers
Related