JS Built-ins
redux-legacyaction-creatorintermediate

Async Action Pattern

πŸ“– Usage Example
function fetchUser(id) {
  return function(dispatch) {
    dispatch({ type: 'FETCH_USER_REQUEST' })
    return fetch('/users/' + id)
      .then(r => r.json())
      .then(user => dispatch({ type: 'FETCH_USER_SUCCESS', payload: user }))
      .catch(err => dispatch({ type: 'FETCH_USER_FAILURE', error: err.message }))
  }
}

The request/success/failure pattern gives the UI clear signals to show loading spinners and error messages.

Async Action Pattern

A typical thunk action creator dispatches three actions for async operations:

  1. A REQUEST action immediately (shows a loading state)
  2. A SUCCESS action when the data arrives
  3. A FAILURE action if something goes wrong
function fetchUser(id) {
  return function(dispatch) {
    dispatch({ type: 'FETCH_USER_REQUEST' })
    return fetch('/users/' + id)
      .then(r => r.json())
      .then(user => dispatch({ type: 'FETCH_USER_SUCCESS', payload: user }))
  }
}

Challenge: Implement fetchUser(id) that dispatches 'FETCH_USER_REQUEST' immediately and returns a Promise that resolves with a success dispatch.

πŸ’‘ Hints (2)
  • β€’ The thunk must dispatch `FETCH_USER_REQUEST` before the async operation starts.
  • β€’ Only the synchronous request dispatch is tested here β€” the Promise resolves asynchronously.