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?
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
The utility should get the state as an argument.
Because you want to use the utility in the components (views) you can store the state in a member variable on your smart component (the one using connect()
function) via mapStateToProps(state)
callback.
then you can pass this member to your dumb components.
Hi late for this post please take a look of my below code. Thanks
import { store } from "../../../redux/store";
// getting data from redux
const state = store.getState();
//i am fetching estimator data
const data = state.valuemodel.estimatorData;
© 2022 - 2024 — McMap. All rights reserved.