Use Redux middleware to reduce redux thunk api action boilerplate
If you have written code like below to call api using redux thunk again and again and got frustrated with it. There is a way to avoid this boilerplate using redux middleware.
const FETCH_POSTS_LOADING = 'FETCH_POSTS_LOADING'
const FETCH_POSTS_SUCCESS = 'FETCH_POSTS_SUCCESS'
const FETCH_POSTS_FAILURE = 'FETCH_POSTS_FAILURE'
export const postLoading = () => ({ type: FETCH_POSTS_LOADING })
export const postLoadingSuccess = (response) => ({
type: FETCH_POSTS_SUCCESS,
payload: response
})
export const postLoadingFailure = (errors) => ({
type: FETCH_POSTS_FAILURE,
payload: errors
})
export function fetchPosts() {
return function (dispatch) {
dispatch(postLoading())
return axios.request({
url: 'https://www.example.come/posts.json',
method: 'get'
})
.then(({ data }) => {
dispatch(postLoadingSuccess(data))
})
.catch(errors => {
next(postLoadingFailure(errors))
})
}
}
Here is the blog post that shows the approach to reduce this boilerplate