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!
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.
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.
getState. It helps you retrieve the current state of your Redux store.
You just need to export the store from the module where it created with createStore() . Also, it shouldn't pollute the global window object.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With