Blog>
Snippets

Handling Asynchronous Data Fetching with Redux Thunk

Illustrate how to use Redux Thunk middleware for asynchronous data fetching, including dispatching actions for loading states and successful data retrieval.
// actions.js
export const fetchDataRequest = () => ({
  type: 'FETCH_DATA_REQUEST'
});

export const fetchDataSuccess = (data) => ({
  type: 'FETCH_DATA_SUCCESS',
  payload: data
});

export const fetchDataFailure = (error) => ({
  type: 'FETCH_DATA_FAILURE',
  payload: error
});
Action creators for fetching data, handling the request, success, and failure states.
// thunks.js
import { fetchDataRequest, fetchDataSuccess, fetchDataFailure } from './actions';

// Thunk function to fetch data
export const fetchData = () => {
  return (dispatch) => {
    dispatch(fetchDataRequest());
    fetch('/api/data')
      .then((response) => response.json())
      .then((data) => dispatch(fetchDataSuccess(data)))
      .catch((error) => dispatch(fetchDataFailure(error.message)));
  };
};
A thunk function that dispatches actions to handle different stages of the asynchronous data fetching process.
// store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

export default store;
Creation of the Redux store with the thunk middleware applied.