how to create an async thunk in typescript

To create an async thunk in TypeScript using Redux Toolkit and Redux Thunk, follow these steps:

  1. Install redux-thunk package: npm install redux-thunk

  2. Install @types/redux-thunk for TypeScript type definitions: npm install --save-dev @types/redux-thunk

  3. Create a thunk using createAsyncThunk() function from redux-toolkit:

index.ts
import { createAsyncThunk } from '@reduxjs/toolkit';

export const fetchData = createAsyncThunk(
  'data/fetchData',
  async (url: string) => {
    const response = await fetch(url);
    const data = await response.json();
    return data;
  }
);
247 chars
11 lines

The first argument to createAsyncThunk() is the name of the thunk action, and the second argument is an async function that returns the result of the API call.

  1. Add a slice using createSlice() function:
index.ts
import { createSlice } from '@reduxjs/toolkit';
import { fetchData } from './thunk';

interface DataState {
  data: any;
  status: 'idle' | 'loading' | 'succeeded' | 'failed';
  error: string | null;
}

const initialState: DataState = {
  data: null,
  status: 'idle',
  error: null
};

const dataSlice = createSlice({
  name: 'data',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(fetchData.pending, (state) => {
      state.status = 'loading';
    });
    builder.addCase(fetchData.fulfilled, (state, action) => {
      state.status = 'succeeded';
      state.data = action.payload;
    });
    builder.addCase(fetchData.rejected, (state, action) => {
      state.status = 'failed';
      state.error = action.error.message;
    });
  }
});

export default dataSlice.reducer;
815 chars
36 lines
  1. Dispatch the thunk action using dispatch() function:
index.ts
import { useDispatch } from 'react-redux';
import { fetchData } from './thunk';

function App() {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchData('https://api.example.com/data'));
  }, [dispatch]);
  
  //...
}
241 chars
13 lines

This will trigger the API call and update the Redux state accordingly as the request status changes (pending, fulfilled, or rejected).

gistlibby LogSnag