Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React/Redux: Global function that can dispatch actions?

Tags:

reactjs

redux

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!

like image 717
djbuttery Avatar asked Jul 22 '16 17:07

djbuttery


People also ask

Which of the following functions can be used to dispatch actions in Redux?

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.

What is an action in Redux can I dispatch an action in reducer?

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.

Does Redux have a dispatcher?

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.


2 Answers

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.

like image 100
Aaron Beall Avatar answered Oct 06 '22 03:10

Aaron Beall


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

like image 30
Grynn Avatar answered Oct 06 '22 05:10

Grynn