Basic createAsyncThunk for Data Fetching
Show a simple use case of createAsyncThunk to fetch data from an API and dispatch the results to the store.
import { createAsyncThunk } from '@reduxjs/toolkit';
// Define the async thunk for fetching data from an API
export const fetchData = createAsyncThunk(
'data/fetch', // the action type prefix
async (url, thunkAPI) => {
try {
const response = await fetch(url);
if (!response.ok) {
return thunkAPI.rejectWithValue('Failed to fetch data');
}
const data = await response.json();
return data; // payload will be automatically dispatched in the fulfilled action
} catch (error) {
return thunkAPI.rejectWithValue('Network error');
}
}
);
This code defines an async thunk called 'fetchData' that takes a URL for fetching data from an API. It makes an asynchronous GET request to the API, processes the response, and either returns the JSON-parsed data for success (which can then automatically trigger a fulfilled action in the slice) or uses the 'rejectWithValue' to handle errors (which can trigger a rejected action in the slice).
import { createSlice } from '@reduxjs/toolkit';
import { fetchData } from './pathToYourAsyncThunk';
const dataSlice = createSlice({
name: 'data',
initialState: { value: [], status: 'idle', error: null },
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchData.pending, (state) => {
state.status = 'loading';
})
.addCase(fetchData.fulfilled, (state, action) => {
state.status = 'succeeded';
state.value = action.payload; // Assuming the payload is the data array
})
.addCase(fetchData.rejected, (state, action) => {
state.status = 'failed';
state.error = action.payload; // Assuming the payload is the error message
});
}
});
export default dataSlice.reducer;
This code sets up a Redux slice using createSlice, which will respond to the async thunk's actions. It listens for pending, fulfilled, and rejected actions dispatched by the 'fetchData' async thunk and updates the state accordingly. In the case of a fulfilled action, it saves the payload (expected to be the fetched data) to the state. For pending and rejected actions, it updates the fetch status and potentially stores an error message.