I have created a reducer called auth and persisted in this reducer.
I want to get auth value outside of the functional component or class component, for example in the utils. How can I do that?
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LoginSuccess = (payload) => {
return {
type: LOGIN_SUCCESS,
payload
};
};
import { LOGIN_SUCCESS } from './authAction';
// INITIAL TIMER STATE
const initialState = {
user: {}
};
// Auth REDUCER
export const authReducer = (state = initialState, { type, payload }) => {
switch (type) {
case LOGIN_SUCCESS:
return { ...state, user: payload };
default:
return state;
}
};
const reducers = {
auth: authReducer
};
const persistConfig = {
key: 'primary',
storage,
whitelist: ['auth'] // place to select which state you want to persist
};
This is not really "react-redux" way. Your store is a part of react application that is just big react component. However, you can create your store in separate module outside of your application and use it where you want importing instance of your store.
For example, you are creating your store in store.js:
// store.js
export default createStore(reducer, preloadedState, enhancers);
Then, you can import it inside your react application
// app.jsx
import store from '/path/to/store';
import { Provider } from 'react-redux';
function App () {
<Provider store={store}>{everything else}</Provider>
}
and inside your utils
// my-util.js
import store from '/path/to/store';
function util() {
// do whatever you want with same instance of store
// for example, return current state
return store.getState()
}
You can subscribe to store, if you need or just get current state. Or you can do complex stuff with replacing reducers for seamless client side updates.