user1189352 user1189352 - 3 years ago 166
React JSX Question

Accessing getState() in a non-Action file nor Component

Is there any way I can access getState() from a non-React Component nor an Action file?

I have a Util file that needs to be able to call getState() (or just any way to get the most updated state). Usually I just pass in part of the state that I need for the function, but I have one particular function that loops and needs to get the latest function every time it does loop.

I was reading more into connect() but it seems like it only works for Components. I was looking into Middleware, but it seems like that only interacts with executing Actions and I'm just at a road block where I don't know how to move forward.

Thank you

Answer Source

You might consider leveraging the subscribe(listener) method in the Redux Store.

The subscribe method allows you to attach a callback that is called every time the state tree may have potentially changed. This would let you call getState() inside the listener to get the current state tree.

The subscribe method is a low level API and is a bit clunky. The documentation for Redux also provides some linking to examples leveraging the Observable property of the Redux store so you can do something a bit more abstracted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download