I don't understand the difference between the two statements below. Why does returning a function twice in the logger make it any different ?
const logger = store => next => action => {
let result
console.groupCollapsed("dispatching", action.type)
console.log('prev state', store.getState())
console.log('action', action)
result = next(action)
console.log('next state', store.getState())
console.groupEnd()
return result
}
const logger = (store, next, action) => {
let result
console.groupCollapsed("dispatching", action.type)
console.log('prev state', store.getState())
console.log('action', action)
result = next(action)
console.log('next state', store.getState())
console.groupEnd()
return result
}
It is so you can partially apply parameters to the function. For example, you may only know (or have in scope) your store
and next
function at a particular point in time. Later on, during execution, you may then have your action
parameter but the store
is out of scope.
Therefore, you partially apply the first two parameters and then pass the returned function around so it can finally be executed with the third parameter at a later stage. When it is finally executed with the third parameter it has access to the first two parameters because they were enclosed in the partially applied function. An example might clarify:
const store = {
getState: () => 'foo'
}
// this can be passed around, it creates a closure around store so will have access to it later
const partialLogger = logger(store)((ac) => ({
ac,
bar: 2
}));
// some time later - execute
const res = partialLogger({ type: 'baz' });
console.log('>res', res);