DEV Community

hemanth.hm
hemanth.hm

Posted on

10 1

async actions in redux

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (2)

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

Yeah, rather:

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

What say?

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️