Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the redux store from a library?

Tags:

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!

like image 721
alexmngn Avatar asked Mar 26 '16 19:03

alexmngn


People also ask

What is the proper way to access Redux store?

The best way to access your store in a component is to use the connect() function, that creates a new component that wraps around your existing one.

Where is Redux store stored?

The state in Redux is stored in memory. This means that, if you refresh the page the state gets wiped out. The state in redux is just a variable that persists in memory because it is referenced by all redux functions.

Which method is used to read the Redux store?

getState. It helps you retrieve the current state of your Redux store.

How can we access a Redux store outside a React component?

You just need to export the store from the module where it created with createStore() . Also, it shouldn't pollute the global window object.


1 Answers

My impulse would be swap the params:

import { authenticate } from 'libraries/session';


export function configureLogin(store) {
    var {dispatch, subscribe, getState} = store;
    return (email, password) => {
        dispatch(loginRequest());

        return authenticate(email, password, dispatch) // <- I don't why dispatch needs to be included, but I'll take ur word for it
        .then(() => dispatch(loginSuccess())
        .catch(json => dispatch(loginError()));
    };
};

// usage
import { configureLogin } from './service/login';
var store = createStore();
var login = configureLogin(store);
login(email, password);
like image 151
Ashley Coolman Avatar answered Oct 12 '22 09:10

Ashley Coolman