Blog>
Snippets

Basic Recursive fetch with createAsyncThunk

Demonstrate a simple recursive API request using createAsyncThunk to traverse a paginated resource until all pages are fetched.
import { createAsyncThunk } from '@reduxjs/toolkit';

// Define the async thunk for fetching paginated data
export const fetchAllPages = createAsyncThunk(
  'data/fetchAllPages',
  async (_, { dispatch, getState }) => {
    let page = 1;
    let hasNextPage = true;
    let allData = [];

    while (hasNextPage) {
      // Perform the fetch for the current page
      const response = await fetch(`/api/data?page=${page}`);
      const data = await response.json();

      // Add the fetched data to the cumulative list
      allData = [...allData, ...data.results];
      hasNextPage = data.next !== null;
      page++;

      // Optionally dispatch an action to store current page results
      // dispatch(storeCurrentPageData(data.results));
    }

    // Return all data once all pages are fetched
    return allData;
  }
);
This code defines an async thunk using createAsyncThunk from Redux Toolkit to recursively fetch all pages of a paginated API resource. It continues fetching until there are no more pages indicated by the 'next' property being null. Each fetched page's data is added to an accumulating array which is then returned when all pages have been fetched.