Blog>
Snippets

Using TypeScript with Redux thunk for asynchronous actions

Illustrate the use of TypeScript with Redux thunk to type-check asynchronous action creators that return functions in Redux 5.0.0.
import { Action, Dispatch } from 'redux';
import { ThunkAction } from 'redux-thunk';
import axios from 'axios';

// Define the state type
interface ExampleState {
    data: string;
}

// Define the action types
enum ExampleActionTypes {
    FETCH_START = 'FETCH_START',
    FETCH_SUCCESS = 'FETCH_SUCCESS',
    FETCH_ERROR = 'FETCH_ERROR'
}

// Action Interfaces
interface FetchStartAction {
    type: ExampleActionTypes.FETCH_START;
}

interface FetchSuccessAction {
    type: ExampleActionTypes.FETCH_SUCCESS;
    payload: string;
}

interface FetchErrorAction {
    type: ExampleActionTypes.FETCH_ERROR;
    error: string;
}

// Union Action Type
type ExampleAction = FetchStartAction | FetchSuccessAction | FetchErrorAction;

// Action Creators
export const fetchStart = (): FetchStartAction => {
    return {
        type: ExampleActionTypes.FETCH_START
    };
};

export const fetchSuccess = (payload: string): FetchSuccessAction => {
    return {
        type: ExampleActionTypes.FETCH_SUCCESS,
        payload
    };
};

export const fetchError = (error: string): FetchErrorAction => {
    return {
        type: ExampleActionTypes.FETCH_ERROR,
        error
    };
};

// Thunk Action
export const fetchData = (): ThunkAction<void, ExampleState, unknown, Action<string>> => {
    return async (dispatch: Dispatch) => {
        dispatch(fetchStart());
        try {
            const response = await axios.get('/api/data');
            dispatch(fetchSuccess(response.data));
        } catch (error) {
            dispatch(fetchError(error.message));
        }
    };
};
This code snippet demonstrates how to use TypeScript with Redux Thunk to type-check actions and action creators for asynchronous operations. It includes an interface for the state, action type enums, action interfaces, a union action type, and typed action creators. The fetchData function is an asynchronous thunk action creator which dispatches actions based on the result of an API call.