Hemanth's scribes

web

Redux Async Actions

Author Photo

Hemanth HM

Thumbnail

The most common question I hear post intro to Redux is: “How do I fetch some data in actions?”

Most 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.

Vanilla Approach

Let’s see a quick example to make an API request using the vanilla approach (without middleware).

Initial State

const initialState = {
  loading: false,
  error: false,
  comic: null
}

### Reducer
javascript
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'FETCHING_COMIC':
      return { ...state, loading: true }
    case 'FETCH_COMIC_SUCCESS':
      return { ...state, loading: false, comic: action.comic }
    case 'FETCH_COMIC_FAILED':
      return { ...state, loading: false, error: action.error }
    default:
      return state
  }
}

### Store and Dispatch
javascript
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 })
  )

### Render
javascript
const render = function(state) {
  let xkcd = document.querySelector('#xkcd');
  xkcd.src = state.comic.url;
  xkcd.alt = state.comic.title;
}

For more complex use cases, consider redux-thunk, redux-promise, or redux-saga.

#javascript#redux#react
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Staff Engineer at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions..