Bill
Bill

Reputation: 19268

Redux Middleware currying

I have this question in my head, not sure if this is validate or not, below it's an example of redux middle console log out the store.

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

I can see it's using currying, so in redux is calling as logger(store)(store.dispatch)(action) (Correct me if i am wrong). My question is why we currying here instead just

(store, next, action) => { // do the rest }

Thanks for any suggestion I am slowly moving into functional programming too to get my head up rhythm with it.

Upvotes: 0

Views: 549

Answers (1)

chzhuo
chzhuo

Reputation: 44

I think redux wants to provide three hooks to developers.

We can split the call chain logger(store)(next)(action) into

let haveStoreAndDispatch = logger(store);
let haveNext = haveStoreAndDispatch(next);
let haveAction = haveNext(action);

Then we get three hook functions. In haveStoreAndDispatch callback function, store have been created.
In haveNext callback function, we have get the next middleware.
In HaveAction callback function, we can do something with the previous middleware's result action.

Callbacks haveStoreAndDispatch and haveNext just be called only once in applyMiddleware(...middlewares)(createStore).

Upvotes: 2

Related Questions