fetchNextPage method

Future<void> fetchNextPage()

Fetch the next page of data.

If already fetching or no next page exists, this does nothing.

Implementation

Future<void> fetchNextPage() async {
  if (isFetchingNextPage.value || !hasNextPage.value || isDisposed) {
    return;
  }

  isFetchingNextPage.value = true;
  update(); // Update UI to show loading footer

  // Create token for this specific operation
  _nextPageCancelToken?.cancel('New next page fetch started');
  final token = ZenCancelToken('Fetching next page');
  _nextPageCancelToken = token;

  try {
    // 1. Fetch the new page using the stored param
    final newPage = await infiniteFetcher(_nextPageParam, token);

    if (isDisposed || token.isCancelled) return;

    // 2. Append to existing pages
    final currentPages = data.value ?? [];
    final allPages = [...currentPages, newPage];

    // 3. Update the reactive data
    _updateDataAndCache(allPages);

    // 4. Calculate the cursor for the NEXT fetch
    final nextParam = getNextPageParam(newPage, allPages);
    _nextPageParam = nextParam;
    hasNextPage.value = nextParam != null;

    // 5. Ensure status is success
    if (status.value != ZenQueryStatus.success) {
      status.value = ZenQueryStatus.success;
    }

    // Clear any previous errors since this succeeded
    error.value = null;
  } catch (e) {
    _handleFetchError(e, token);
  } finally {
    if (!isDisposed) {
      isFetchingNextPage.value = false;
      if (_nextPageCancelToken == token) {
        _nextPageCancelToken = null;
      }
      update();
    }
  }
}