Blog>
Snippets

Reducers for Handling Pagination Metadata

Provide a code example of reducers that update the Redux store with pagination metadata such as current page, total results, and loading states triggered by paginated API responses.
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

// Async thunk action for fetching paginated data
export const fetchPaginatedData = createAsyncThunk(
    'data/fetchPaginatedData',
    async ({ page }, { rejectWithValue }) => {
        try {
            const response = await someApi.fetchData(page);
            return response.data;
        } catch (error) {
            return rejectWithValue(error.response.data);
        }
    }
);

// Slice for pagination data including metadata
const paginationSlice = createSlice({
    name: 'pagination',
    initialState: {
        currentPage: 1,
        totalResults: 0,
        data: [],
        loading: false,
        error: null
    },
    reducers: {
        // Reducer for resetting pagination
        resetPagination(state) {
            state.currentPage = 1;
            state.totalResults = 0;
            state.data = [];
            state.loading = false;
            state.error = null;
        }
    },
    extraReducers: {
        [fetchPaginatedData.pending]: (state) => {
            state.loading = true;
            state.error = null;
        },
        [fetchPaginatedData.fulfilled]: (state, action) => {
            state.data.push(...action.payload.data);
            state.currentPage = action.payload.currentPage;
            state.totalResults = action.payload.totalResults;
            state.loading = false;
        },
        [fetchPaginatedData.rejected]: (state, action) => {
            state.loading = false;
            state.error = action.payload || 'Failed to fetch data';
        }
    }
});

export default paginationSlice.reducer;
This code example provides a Redux slice using the Redux Toolkit for managing paginated API responses. It includes an async thunk for fetching data, reducers to handle state updates including pagination metadata, and extraReducers to update the loading state and manage successful or failed API responses.