Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access react-redux store outside of component

I have file which exports various utility functions to use across components, and these functions needs to access redux state. How do I import the state object to this file?

like image 1000
Tuomas Toivonen Avatar asked Aug 18 '16 10:08

Tuomas Toivonen


People also ask

How do I access Redux store in react?

createContext() , called ReactReduxContext . React Redux's <Provider> component uses <ReactReduxContext. Provider> to put the Redux store and the current store state into context, and connect uses <ReactReduxContext. Consumer> to read those values and handle updates.

Where is Redux store stored?

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.


2 Answers

connect does not work here if your utility functions are not react elements.

Best idea is, import create store and then use getState function,

import store from 'store/createStore';
const state = store.getState();
like image 164
anoop Avatar answered Sep 22 '22 22:09

anoop


Well, this isn't a simple answer, but after researching this for too long, I found these, which are the only 2 articles that explain anything. They explain how to access the store directly outside of a Component (if you must) and also mention the pure functions / functional programming philosophy as well as potential performance issues with connecting a bunch of non-component functions to the store directly. Personally, I went with @anoop and passed the params around in a single object as deeply as needed.

For connecting directly (which gets the store from this.context the way connect() does, see the discussion here and specifically gaearon's comment on Sep 16, 2015 and Sep 22, 2015. It seems this access can be achieved via connect()

For a little reading on functional programming / pure functions, see the discussion here

like image 35
Mike Avatar answered Sep 25 '22 22:09

Mike