How to access the redux store from a library?

Viewed 1579

I am creating a library for my react application which will handle every API calls related to the session (authenticate, register, refresh token etc...) and this library will need to access the redux store on its own to dispatch actions. The reason behind this is whenever the access token of the user expires, using a setTimeout I need to call an action creator that will call my API to refresh the token, and update the application redux store with the new session data.

So I was thinking to pass the dispatch method to the library whenever I call it for the first time, but I'm not sure that's the best way to do it.

Or I could also create an initialize() method that will pass the dispatch to the library.

import { authenticate } from 'libraries/session';

export function login(email, password) {
    return (dispatch) => {
        dispatch(loginRequest());

        return authenticate(email, password, dispatch) // dispatch is passed here, so I can use it later in the library
        .then(() => (
            dispatch(loginSuccess())
        ))
        .catch((json) => (
            dispatch(loginError());
        ));
    };
};

I haven't tried this code yet, it's more of a brainstorming for now.

Would you have any suggestion of the best way to handle this?

Thanks!

1 Answers
Related