I am having a helper class which provies info about the logged in user. I would like to have it as a static method and use it in several places ( which are not react components)
How to get access the redux store value in a class model ?
I am having a helper class which provies info about the logged in user. I would like to have it as a static method and use it in several places ( which are not react components)
How to get access the redux store value in a class model ?
If you can manage this in your application it would be cleaner (and more testable) to pass it around with dependency injection (DI) as opposed to using a global variable, static or singleton. In a simple form you could just pass it in the constructor like this:
var store = createStore(...);
var app = new AppClass(store);
If you're not using a bundler like Webpack, Lukas Katayama's answer should work window.store = createStore(...)
but if you are using one, you can also expose your redux store by exporting it and importing where you need it.
//store.js
export const store = createStore(...);
//other file
import { store } from './store.js';
const someFuncOrClass = (...) => {
const user = store.getState().userInfo;
}
One way could be set a global variable
window.store = createStore(...)
and use it, accessing window.store
Looks like a straight forward implementation. You can create a getter for store in the same file where you creatStore(...)
.
store.js
import { createStore } from 'redux';
let store = {};
export default function store(...) {
/*
* things to do before creating store
*/
store = createStore(...);
return store;
}
export function getStore() {
return store;
}
helper.js
import { getStore } from './store';
export function getUserInfo() {
const store = getStore();
const globalState = store.getState();
return globalState.userInfo;
}