Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reach redux state from static function

I have a React Native application where I have a class which name is Helpers. These are a set of application related static helper function. Mostly I call them like Helpers.functionName(). What is the best way to reach the redux store from this static method? I want to modify it and read it.

I have the Helpers like this:

class Helpers extends Component {
  static getState(){
    return state;
  }
}

I tried to use the connect, but inside the getState function the this.props is undefined.

like image 574
PumpkinSeed Avatar asked Jul 04 '17 11:07

PumpkinSeed


2 Answers

One way would be to pass store as argument to each static function that requires it. Or you could make store global variable and access it as such.

I would hesitate though to describe any of those ways as best, or use any other positive adjective for that matter. Redux can be used in many ways, but I think intention was to discourage store access as global.

Also note that changing the store directly from your helper functions is a whole another level of no-no. Intention of redux is that only reducer functions change state in response to dispatched actions.

Lastly, is Helpers really a component that you are using, or just container for bunch of static functions? If later, than it is probably misleading to derive it from Component.

like image 73
Davorin Ruševljan Avatar answered Nov 15 '22 05:11

Davorin Ruševljan


If you used the Provider component, so you can access to the redux store (and by consequence to the state of your store), using the context API provided by React.

In order to expose the context, you have to define the contextTypes inside your Helpers components.

static contextTypes = {
  store: PropTypes.object
}

After that, inside your component you can read the store from this.context

like image 35
Ematipico Avatar answered Nov 15 '22 05:11

Ematipico