Reading 38 - AvreyBrown-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. Usually, for any API request you'll want to dispatch at least three different kinds of actions:

An action informing the reducers that the request began.

The reducers may handle this action by toggling an isFetching flag in the state. This way the UI knows it's time to show a spinner.

An action informing the reducers that the request finished successfully.

The reducers may handle this action by merging the new data into the state they manage and resetting isFetching. The UI would hide the spinner, and display the fetched data.

An action informing the reducers that the request failed.

The reducers may handle this action by resetting isFetching. Additionally, some reducers may want to store the error message so the UI can display it.

You may use a dedicated status field in your actions:

{ type: 'FETCH_POSTS' } { type: 'FETCH_POSTS', status: 'error', error: 'Oops' } { type: 'FETCH_POSTS', status: 'success', response: { ... } }

Or you can define separate types for them:

{ type: 'FETCH_POSTS_REQUEST' } { type: 'FETCH_POSTS_FAILURE', error: 'Oops' } { type: 'FETCH_POSTS_SUCCESS', response: { ... } }

Synchronous Action Creators

 actions.js (Synchronous)
 export const SELECT_SUBREDDIT = 'SELECT_SUBREDDIT'

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

Copy They can also press a “refresh” button to update it:

 export const INVALIDATE_SUBREDDIT = 'INVALIDATE_SUBREDDIT'

 export function invalidateSubreddit(subreddit) {
   return {
     type: INVALIDATE_SUBREDDIT,
     subreddit
   }
 }

Copy These were the actions governed by the user interaction. We will also have another kind of action, governed by the network requests. We will see how to dispatch them later, but for now, we just want to define them.

When it's time to fetch the posts for some subreddit, we will dispatch a REQUEST_POSTS action:

export const REQUEST_POSTS = 'REQUEST_POSTS'

function requestPosts(subreddit) {
   return {
     type: REQUEST_POSTS,
     subreddit
   }
 }