Using createAsyncThunk for API Calls
Present how to use `createAsyncThunk` to handle asynchronous API calls with pending, fulfilled, and rejected action types.
// import the necessary functions
import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
// Define an async thunk that makes an API call
export const fetchUserData = createAsyncThunk(
'user/fetchData',
async (userId, thunkAPI) => {
try {
const response = await axios.get(`/api/user/${userId}`);
return response.data;
} catch (error) {
return thunkAPI.rejectWithValue(error.response.data);
}
}
);
This piece of code imports 'createAsyncThunk' from Redux Toolkit and axios for making HTTP requests. It defines an asynchronous thunk named 'fetchUserData' that takes a userId as an argument, then performs a GET request to fetch the user's data. If the request is successful, it returns the response data; if it fails, it returns a rejection with the error response data.
// In your slice file
import { createSlice } from '@reduxjs/toolkit';
import { fetchUserData } from './pathToYourAsyncThunks';
export const userSlice = createSlice({
name: 'user',
initialState: {
data: null,
loading: false,
error: null,
},
extraReducers: {
[fetchUserData.pending]: (state, action) => {
state.loading = true;
state.error = null;
},
[fetchUserData.fulfilled]: (state, action) => {
state.loading = false;
state.data = action.payload;
},
[fetchUserData.rejected]: (state, action) => {
state.loading = false;
state.error = action.payload;
}
}
});
This piece of code defines a slice to handle user data fetched by the `fetchUserData` async thunk. The slice has three extra reducers for the pending, fulfilled, and rejected actions produced by `fetchUserData`. These reducers update the state to reflect the loading status, the fetched data, or an occurred error, respectively.