How to access react-redux store outside of component
Asked Answered
D

4

13

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?

Dudley answered 18/8, 2016 at 10:49 Comment(1)
See Also: What is the best way to access redux store outside a react component?Rosetterosewall
R
13

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();
Rib answered 18/8, 2016 at 15:5 Comment(2)
I ended up just passing the necessary props to utility function from container componentDudley
It gives only initial data of redux not updated.Veld
U
4

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

Uphold answered 8/1, 2017 at 5:40 Comment(0)
P
0

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.

Perice answered 18/8, 2016 at 10:59 Comment(1)
You'd have to pass the members to the utility EVERY time you want to use it, would be great if the utility can just access those members so we don't repeat code...Boutis
T
0

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;

enter image description here

Toothlike answered 18/4, 2023 at 9:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.