3

I see the following two styles of action in Redux:

From the documentation:

export function createFoo(foo) {
  return {
    type: ActionTypes.CREATE_AUTHOR,,
    foo
  }
}

...and from another tutorial (PluralSight):

export function createFoo(foo) {
  var newFoo = FooApi.saveFoo(foo);

  Dispatcher.dispatch({
    actionType: ActionTypes.CREATE_FOO,
    foo: newFoo
  });
}

The latter appears to have more responsibility, creating an author instance and dispatching an event.

Why is there a difference in approach? Are these two separate idioms (possibly one expects middleware to perform dispatching?).

Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • There would be a difference in the way you have connected actions to the component. In first case from React DOCS, you would make use of connect function to provide you with dispatch – Shubham Khatri Jun 26 '17 at 18:31
  • In the first case, the reducers would not be pure then? (because the reducers would presumably have to encapsulate the logic for calling the API to saveFoo, for example) – Ben Aston Jun 26 '17 at 18:34
  • The Reducer simply receives the action and then updates the state based on the action. Also if you configure your store correctly, all the reducer will receive the action. – Shubham Khatri Jun 26 '17 at 18:36

1 Answers1

2

The second example appears to be from the original Flux implementation, not Redux. Redux does not have a separate "dispatcher", and requires that actions have a type field.

You may be interested in reading my blog post The Tao of Redux, Part 1 - Implementation and Intent, which goes into detail on the actual technical limitations that Redux requires and why, and the history and original intent behind its creation.

markerikson
  • 63,178
  • 10
  • 141
  • 157
  • Thank you. So flux has a dispatcher. Redux is an implementation of flux that does away with the concept? (Reading your link now...). My second example includes logic for an API call for example. Where in redux would that logic sit? The reducer, or if I wanted a pure reducer, a thunk? – Ben Aston Jun 26 '17 at 18:39
  • Definitely **NOT** in a reducer. Reducers should _always_ be pure functions - `(state, action) => newState`. For more info on how side effects fit into Redux, see [the Redux FAQ entry on side effects](http://redux.js.org/docs/faq/Actions.html#actions-side-effects), and especially Dan's SO answers on [using middleware for async work](http://stackoverflow.com/questions/34570758/why-do-we-need-middleware-for-async-flow-in-redux) and [handling timeouts in Redux](http://stackoverflow.com/questions/35411423/how-to-dispatch-a-redux-action-with-a-timeout/35415559). – markerikson Jun 26 '17 at 19:36