Blog>
Snippets

Implementing Redux Thunk Middleware for Async Actions

Create an example showing how to write a Redux thunk to handle asynchronous operations within action creators.
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

// Define the initial state of our store
const initialState = { data: [], loading: false, error: null };

// Example of an async action creator using redux-thunk
const fetchData = () => (dispatch) => {
    // First dispatch an immediate synchronous action to start the loading process
    dispatch({ type: 'FETCH_DATA_START' });
    
    // Then perform the asynchronous task, e.g., fetching data from an API
    fetch('/data')
        .then(response => response.json())
        .then(data => {
            // Dispatch another action to signal the completion and pass the data
            dispatch({ type: 'FETCH_DATA_SUCCESS', payload: data });
        })
        .catch(error => {
            // In case of error, dispatch an action with the error
            dispatch({ type: 'FETCH_DATA_ERROR', payload: error });
        });
};

// Reducer to handle the actions
const rootReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'FETCH_DATA_START':
            return { ...state, loading: true, error: null };
        case 'FETCH_DATA_SUCCESS':
            return { ...state, loading: false, data: action.payload };
        case 'FETCH_DATA_ERROR':
            return { ...state, loading: false, error: action.payload };
        default:
            return state;
    }
};

// Create store with the rootReducer and apply the thunk middleware
const store = createStore(
    rootReducer,
    applyMiddleware(thunk)
);
This code snippet includes a Redux store setup where redux-thunk is applied as middleware. The `fetchData` function is an example of a thunk action creator that performs an asynchronous fetch request. The `rootReducer` updates the state based on the actions dispatched before, during, and after the async task completes.