I am looking to implement a React/Redux function as a global utility that has the ability to dispatch actions.
This is not a Component/Container. Simply a global/static function that can be imported and invoked by others.
Is this possible?
Thank you in advance for any ideas/suggestions you can provide!
You can dispatch an action by directly using store. dispatch(). However, it is more likely that you access it with react-Redux helper method called connect(). You can also use bindActionCreators() method to bind many action creators with dispatch function.
Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.
Redux doesn't have a Dispatcher or support many stores. Instead, there is just a single store with a single root reducing function. As your app grows, instead of adding stores, you split the root reducer into smaller reducers independently operating on the different parts of the state tree.
The dispatch
comes from the Store
so you just need a global reference to your Store
.
So suppose your application root looks something like this:
const store = createStore(rootReducer);
ReactDOM.render(<Provider store={store} /> ...);
Just export that store
:
export const store = createStore(root);
And from your static util import the store:
import {store} from "../path/to/app/root";
store.dispatch({ ... });
A better way to do this would be to make your util function accept dispatch
as an argument, this way you have no global references to store
.
I'm old school; in app.js I would just do:
window.store = store
That's it - store exposed globally, no need to import etc. This will break server side rendering, but that breaks if you use a global dispatch in any case. See this twitter thread: https://twitter.com/Grynn/status/955485816389685248
Quoting reply from Dan Abramov (in above thread):
Makes testing harder, breaks if there are several such apps in the page (which happens in practice in big products), makes server rendering impossible. Otherwise it's fine sure
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