stackjlei stackjlei - 1 year ago 78
Javascript Question

using redux store's instance of dispatch vs. passing in dispatch as parameter

In the docs, Dan doesn't give much reasoning for changing the way dispatch is passed into middleware. He just says this:

But there's also a different way to enable chaining. The middleware
could accept the next() dispatch function as a parameter instead of
reading it from the store instance.

What is the reason for this? To me, it just looks more weird now that the code inside
will take 2 arguments with store and dispatch, rather than just store alone.

Answer Source

Looking weird is not a problem.

const logger = store => next => action => {
  console.log('dispatching', action)
  let result = next(action)
  console.log('next state', store.getState())
  return result

Note that functional languages have this format by default and there it's completely normal.

The reason this is done is because monkey patching has not established itself as a recommended programming method. Passing the next to the function is more flexible and doesn't require anything of the function being called (a developer's function) thereby placing less burden on the developer and lowering the chances of errors.

Finally, Dan likes to explain why he's coding things a certain way, but as lib users, we lowly developers are not the decision makers. The decision has already been made and this is the way to use middleware in Redux. You can always fork Redux and modify it to your liking but note that the power of Redux is not the code inside the lib, but the code attached to it by 3rd part developers. By not playing along, you'd forgo all that power.

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