in React JS by
Q:

How to make AJAX request in Redux?

1 Answer

0 votes
by

You can use redux-thunk middleware which allows you to define async actions.

Let's take an example of fetching specific account as an AJAX call using fetch API:

export function fetchAccount(id) {
  return dispatch => {
    dispatch(setLoadingAccountState()) // Show a loading spinner
    fetch(`/account/${id}`, (response) => {
      dispatch(doneFetchingAccount()) // Hide loading spinner
      if (response.status === 200) {
        dispatch(setAccount(response.json)) // Use a normal function to set the received state
      } else {
        dispatch(someError)
      }
    })
  }
}

function setAccount(data) {
 return { type: 'SET_Account', data: data }
}

Related questions

0 votes
asked Feb 6, 2020 in JavaScript by rajeshsharma
  • #ajax-request
0 votes
asked Feb 6, 2020 in JavaScript by rajeshsharma
0 votes
0 votes
asked Apr 13 in Redux by Robindeniel
...