middlewareintermediateconst thunk = store => next => action => {
if (typeof action === 'function') {
return action(store.dispatch, store.getState)
}
return next(action)
}
// Thunk action creator:
function loadUser(id) {
return function(dispatch) {
dispatch({ type: 'LOADING' })
fetch('/users/' + id).then(r => r.json()).then(user =>
dispatch({ type: 'LOADED', payload: user })
)
}
}Thunk middleware enables async operations by letting action creators return functions that are called with dispatch and getState.
Redux Thunk lets you dispatch functions instead of plain objects. When the middleware sees a function, it calls it with (dispatch, getState):
const thunk = store => next => action => {
if (typeof action === 'function') {
return action(store.dispatch, store.getState)
}
return next(action)
}
This enables async logic inside action creators.
Challenge: Implement thunk middleware that intercepts function actions and calls them, or forwards plain object actions to next.