Skip to main content
InterviewHubPRO
Section Overview
Q113

Question 113 of 407

Part 5: React Redux State Management (101 - 134)

28%
React Core & Hooks (407 Qs)•Part 5: React Redux State Management (101 - 134)

How to make AJAX request in Redux?

mid LevelMost AskedCode ExampleState Management

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:

javascript
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 };
}