Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Redux Async Actions

| Comments

The most common question I hear post intro to redux is: "How do I fetch some data in actions?"

Most of them would hit the roadblock with: Actions must be plain objects. Use custom middleware for async actions. that is because Actions are meant to be plain JavaScript objects and must have a type property that indicates the type of action being performed.

Let us see a quick example to make an API request say this xkcd comic API.

As there is no community consensus for handling async actions and there are many libs out there that will make things easier in handling async actions, but in this example below we shall take the vanilla approach.

Let us start with an initial state that looks like:

1
2
3
4
5
const initialState = {
  loading: false,
  error: false,
  comic: null
}

a reducer which handle fetching, fetched and failed states of the action.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'FETCHING_COMIC':
      return {
        ...state,
        comic: action.comic
      }
    case 'FETCH_COMIC_SUCCESS':
      return {
        ...state,
        comic: action.comic
      }
    case 'FETCH_COMIC_FAILED':
      return {
        ...state,
        error: action.error
      }
  }
}

a store and dispatch based on the flow:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const store = Redux.createStore(reducer);

store.dispatch({
  type: 'FETCHING_COMIC'
})

fetch('https://xkcd-imgs.herokuapp.com/')
  .then(response => response.json())
  .then(comic => {
    store.dispatch({
      type: 'FETCH_COMIC_SUCCESS',
      comic
    })
  })
  .catch(error => store.dispatch({
    type: 'FETCH_COMIC_FAILED',
    error
  }))

Some mandatory render method (not react this time ;))

1
2
3
4
5
const render = function(state) {
    let xkcd = document.querySelector('#xkcd');
    xkcd.src = state.comic.url;
    xkcd.alt = state.comic.title;
  }

Working code:

Some interesting discussions:

P.S: Thanks to <GreenJello> on the quick review.

Comments