DEV Community

loading...

async actions in redux

hemanth profile image hemanth.hm ・2 min read

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:

const initialState = {
  loading: false,
  error: false,
  comic: null
}
Enter fullscreen mode Exit fullscreen mode

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

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
      }
  }
}
Enter fullscreen mode Exit fullscreen mode

a store and dispatch based on the flow:


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
  }))
Enter fullscreen mode Exit fullscreen mode

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

const render = function(state) {
    let xkcd = document.querySelector('#xkcd');
    xkcd.src = state.comic.url;
    xkcd.alt = state.comic.title;
  }
Enter fullscreen mode Exit fullscreen mode

Working code:

Some interesting discussions:

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

P.P.S: This is a repost from h3manth.com

Discussion (2)

pic
Editor guide
Collapse
chgldev profile image
Chris

Great and easy to grasp examples!
In your reducer example, did you mean to write this for the FETCHING_COMIC case?:

case 'FETCHING_COMIC':
  return {
    ...state,
    loading: true
  }
Collapse
hemanth profile image
hemanth.hm Author

Yeah, rather:

 case 'FETCHING_COMIC':
      return {
        ...state,
        fetching: true,
        comic: action.comic
      }
const initialState = {
  fetching: false,
  error: false,
  comic: null
}

What say?