Accessing Redux Store in a Util file
I believe the store
has a getState(
) method available to you.
Import your created store and then call store.getState()
Check out this example from redux's main site:
http://redux.js.org/docs/api/Store.html#example
function select(state) {
return state.some.deep.property
}
let currentValue
function handleChange() {
let previousValue = currentValue
currentValue = select(store.getState())
if (previousValue !== currentValue) {
console.log(
'Some deep nested property changed from',
previousValue,
'to',
currentValue
)
}
}
You got couple of options, the main options as i see it are:
- pass the store to the function (bah please don't do that!).
- You can write your own middleware that handles certain action types and can dispatch other actions if needed (you also get a free access to the ENTIRE store!).
I think the 2nd option is ideal, as you want your util
to do stuff that reflect in the store or need stuff from the store. So basically your util
wants to be a part of the redux
flow!
Well it's not a component
so you can't "connect" it but it can (and should be in my opinion) ad middleware that sits between your actions and reducers.
You can read about middlewares here.
I would have provided you an example of your use case but you didn't post any meaningful code.
Edit
A followup to your comment:
Its quite basic.
- You have a signature of a function that never changes, just look at
the docs (it uses
currying,
this is another
js
topic you should learn) - You need to inject it to the store when you create it with
applymiddleware
(same as you did withredux-thunk
which is a middleware by itself).
I realy recommend to look at the source code of redux-thunk
the whole 11 lines of it.
You can learn a lot from it.