Reputation: 38
I'm trying to figure out how a Redux createStore function works(what parameters it accepts) with enhancers from the documentation.
what I understand is, "sayHiOnDispatch
" takes a "createStore
" function as a parameter and creates a closure around the inner anonymous function which accepts 3 arguments,
rootReducer, preloadedState, enhancers
finally, it return an object {...store,dispatch:newDispatch}
.
what I don't understand is: 1)Where is sayHiOnDispatch
is being called from?
2)How the anonymous function is getting called?
3)What variable receives the return value of return { ...store, dispatch: newDispatch }
4)What calls the newDispatch
functions?
5)How can I understand the function structure(params, return values, etc..) from the Interface Definition?
export type StoreEnhancer<Ext = {}, StateExt = never> = (
next: StoreEnhancerStoreCreator<Ext, StateExt>
) => StoreEnhancerStoreCreator<Ext, StateExt>
export type StoreEnhancerStoreCreator<Ext = {}, StateExt = never> = <
S = any,
A extends Action = AnyAction
>(
reducer: Reducer<S, A>,
preloadedState?: PreloadedState<S>
) => Store<ExtendState<S, StateExt>, A, StateExt, Ext> & Ext
The redux tutorial code.
export const sayHiOnDispatch = (createStore) => {
return (rootReducer, preloadedState, enhancers) => {
const store = createStore(rootReducer, preloadedState, enhancers)
function newDispatch(action) {
const result = store.dispatch(action)
console.log('Hi!')
return result
}
return { ...store, dispatch: newDispatch }
}
}
Hopefully, someone will provide a fishing-rod for me to fish the fish.
Upvotes: 0
Views: 35
Reputation: 67617
Answering the questions in order:
sayHiOnDispatch
gets called either as return enhancer(createStore)(reducer, preloadedState)
inside of createStore
itself, or on the same line as part of a "composed" enhancer (like compose(applyMiddleware(), sayHiOnDispatch)
)
The anonymous function is called on that same line - it's the return value from enhancer()
The returned {...store, dispatch: newDispatch}
is the actual store
variable, as in const store = createStore()
newDispatch
is the actual store.dispatch
function, so it's called as store.dispatch(someAction)
Yeah, that is definitely a complex type signature :) To be honest I wouldn't worry about it - odds are you won't ever end up writing an enhancer yourself.
Upvotes: 1