My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Use Redux middleware to reduce redux thunk api action boilerplate

Rohan Pujari's photo
Rohan Pujari
·Nov 6, 2020·

1 min read

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