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
}
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
}
}
}
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
}))
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;
}
Working code:
Some interesting discussions:
P.S: Thanks to <GreenJello>
on the quick review.
P.P.S: This is a repost from h3manth.com
Top comments (2)
Great and easy to grasp examples!
In your reducer example, did you mean to write this for the
FETCHING_COMIC
case?:Yeah, rather:
What say?