Configuring createAsyncThunk with Pagination Args
Showcase code for setting up createAsyncThunk to accept page arguments and fetch data from a paginated endpoint.
import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
// Define a type for the Slice State
interface PaginationParams {
page: number;
limit: number;
}
// Define the initial state using that type
const initialState = {
items: [],
page: 1,
limit: 10,
loading: false,
error: null
};
// Async Thunk for fetching paginated data
export const fetchPaginatedData = createAsyncThunk(
'data/fetchPaginatedData',
async ({ page, limit }: PaginationParams, { rejectWithValue }) => {
try {
// Adjust the URL to your paginated endpoint
const response = await axios.get(`/api/data?page=${page}&limit=${limit}`);
return response.data;
} catch (error) {
if (!error.response) {
throw error;
}
// Use `rejectWithValue` to return a custom payload on error
return rejectWithValue(error.response.data);
}
}
);
This code sets up a createAsyncThunk function called 'fetchPaginatedData', which accepts pagination parameters and makes an API request to fetch paginated data. The 'fetchPaginatedData' is designed to be dispatched from a Redux store. It takes an object with 'page' and 'limit' properties and makes a GET request to a hypothetical endpoint. The 'rejectWithValue' function is used to return a custom error payload if the API request fails.