From c127e02a3f5e1af23287ed80128cd148be0aaf67 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 29 Jan 2018 11:17:46 -0600 Subject: [PATCH] Add Dispatch Anywhere With Redux as a react til --- README.md | 3 ++- react/dispatch-anywhere-with-redux.md | 33 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 react/dispatch-anywhere-with-redux.md diff --git a/README.md b/README.md index 8128271..7aaf4dd 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_598 TILs and counting..._ +_599 TILs and counting..._ --- @@ -421,6 +421,7 @@ _598 TILs and counting..._ ### React - [Accessing Env Vars In create-react-app](react/accessing-env-vars-in-create-react-app.md) +- [Dispatch Anywhere With Redux](react/dispatch-anywhere-with-redux.md) - [Force A Component To Only Have One Child](react/force-a-component-to-only-have-one-child.md) - [Inactive And Active Component Styles With Radium](react/inactive-and-active-component-styles-with-radium.md) - [Inline Style Attributes Should Be Camel Cased](react/inline-style-attributes-should-be-camel-cased.md) diff --git a/react/dispatch-anywhere-with-redux.md b/react/dispatch-anywhere-with-redux.md new file mode 100644 index 0000000..717b6eb --- /dev/null +++ b/react/dispatch-anywhere-with-redux.md @@ -0,0 +1,33 @@ +# Dispatch Anywhere With Redux + +Your React app is going to have a single top-level `store` which is +connected to the app with the `Provider` component. Most of the time, when +you create a connected component, you'll create prop functions that dispatch +on a redux action. + +This isn't the only place you can dispatch though. + +If you export your `store`, then it can be imported anywhere along with its +`dispatch` function. + +```javascript +// src/index.js +export const store = createStore(rootReducer); +``` + +```javascript +// src/components/MyComponent.js +import { store } from '../index'; +import { updateData } from '../actions'; + +// ... + + componentDidMount() { + getData().then((json) => { + store.dispatch(updateData(json)); + } + } +``` + +See the [`dispatch`](https://redux.js.org/docs/api/Store.html#dispatch) +documentation for more details.