Blog>
Snippets

Designing the Paginated State Slice

Demonstrate how to structure the Redux state slice to store and handle data for multiple pages, along with their respective loading states and page counts.
// Define the initial state for the paginated data
const initialState = {
    items: [],
    page: 1,
    totalPages: null,
    loading: false,
    error: null,
};

// Define the paginated slice using createSlice from Redux Toolkit
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { fetchData } from '../api';

// Define the async thunk for fetching paginated data
export const fetchPage = createAsyncThunk(
    'paginated/fetchPage',
    async ({ pageNumber }, { rejectWithValue }) => {
        try {
            const response = await fetchData(pageNumber);
            return response.data;
        } catch (error) {
            return rejectWithValue(error.response.data);
        }
    }
);

const paginatedSlice = createSlice({
    name: 'paginated',
    initialState,
    reducers: {},
    extraReducers: {
        [fetchPage.pending]: (state) => {
            state.loading = true;
        },
        [fetchPage.fulfilled]: (state, action) => {
            state.items = action.payload.items;
            state.totalPages = action.payload.totalPages;
            state.page = action.payload.page;
            state.loading = false;
        },
        [fetchPage.rejected]: (state, action) => {
            state.error = action.payload;
            state.loading = false;
        },
    },
});

export default paginatedSlice.reducer;
This code snippet creates a Redux state slice for storing and handling paginated data. It defines an initial state with items (data for the current page), page count, total pages, loading state, and error state. 'createAsyncThunk' is used to define an asynchronous action creator to fetch data for a specific page. The 'paginatedSlice' uses 'createSlice' to automatically generate actions and handle the different states of fetching paginated data: pending, fulfilled, and rejected.