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?
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.
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.
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With