JS Built-ins
redux-legacymiddlewareintermediate

Thunk Middleware

πŸ“– Usage Example
const 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.

Thunk Middleware

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.

πŸ’‘ Hints (2)
  • β€’ `typeof action === 'function'` is the check that distinguishes a thunk from a plain action.
  • β€’ Pass `store.dispatch` (not `next`) to the thunk so it can dispatch additional actions.