/  Technology   /  How to make ajax request in redux?
r

How to make ajax request in redux?

 

In Recent Web applications, the backend is separated from the frontend side. Therefore, it needs to fetching data from a remote endpoint(server), by making AJAX requests.

Here is an example of making an ajax request using Redux.

const booksReducer = (state = {}, action) => {
  switch (action.type) {
    case 'RESOLVED_GET_BOOK':
      return action.data;
    default:
      return state;
  }
};
export default booksReducer;

In the above code we are creating an action using redux and passing a switch case condition, If action.type is of “RESOLVED_GET_BOOK” only then will the data be passed. Otherwise we are sending empty state.

Here we can create our async action or api call.

export const getBook() {
  return fetch('/api/data')
    .then(response => response.json())
    .then(json => dispatch(resolvedGetBook(json)))
}
export const resolvedGetBook(data) {
  return {
    type: 'RESOLVED_GET_BOOK',
    data: data
  }
}

We have fetched the data from the api and stored it in the dispatch(resolvedGetBook(json))) and in the component we are exporting the data fetched to the state using Redux.

Thus this is how we can create ajax requests using Redux

 

Leave a comment