Async Actions - sarahduv-401-advanced-javascript/seattle-javascript-401d32 GitHub Wiki

Actions

  • When you call an asynchronous API, there are two crucial moments in time: the moment you start the call, and the moment when you receive an answer (or a timeout).
  • Each of these two moments usually require a change in the application state; to do that, you need to dispatch normal actions that will be processed by reducers synchronously.

Three different kinds of actions

  • An action informing the reducers that the request began.
  • An action informing the reducers that the request finished successfully.
  • An action informing the reducers that the request failed.

Synchronous action creators

export const SELECT_SUBREDDIT = 'SELECT_SUBREDDIT'

export function selectSubreddit(subreddit) {
  return {
    type: SELECT_SUBREDDIT,
    subreddit
  }
}

Async action creators

  • By using this specific middleware, an action creator can return a function instead of an action object. This way, the action creator becomes a thunk.
  • When an action creator returns a function, that function will get executed by the Redux Thunk middleware. This function doesn't need to be pure; it is thus allowed to have side effects, including executing asynchronous API calls. The function can also dispatch actions—like those synchronous actions we defined earlier.

Source: https://redux.js.org/advanced/async-actions