3

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 ?

Jaffer Sathick
  • 466
  • 1
  • 10
  • 21

4 Answers4

1

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);
Wouter de Winter
  • 701
  • 7
  • 11
1

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;
}
jpdelatorre
  • 3,573
  • 1
  • 20
  • 25
0

One way could be set a global variable

window.store = createStore(...)

and use it, accessing window.store

Lucas Katayama
  • 4,445
  • 27
  • 34
0

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;
}
yadhu
  • 15,423
  • 7
  • 32
  • 49