Examples and End-to-End Tests
This module provides comprehensive example applications and end-to-end (E2E) tests that illustrate practical use cases of the SWR data fetching and state management library. It serves to demonstrate the library's capabilities in real-world scenarios and to validate core behaviors such as concurrency handling, retry mechanisms, suspense integration, mutation workflows, and subscription-based real-time updates.
Purpose and Core Concepts
The Examples and End-to-End Tests topic exists to:
Showcase how various SWR hooks and features can be applied in actual applications.
Provide reference implementations that clarify best practices and common patterns.
Ensure robustness and correctness of the library through automated E2E testing.
Validate integration with React Suspense, error boundaries, retries, infinite loading, mutations, and subscriptions.
Help developers understand the interaction between hooks, middleware, and React components in complex scenarios.
By walking through these examples and tests, users gain insight into the practical application of SWR's advanced features beyond the core API.
Key Example Applications
1. Infinite Scroll Example
This example demonstrates how to implement paginated data fetching with infinite loading using the useSWRInfinite hook. It manages page sizes, concatenates data from multiple pages, and supports refreshing and clearing the data set.
Core idea: Fetch data page-by-page from a paginated API endpoint and seamlessly load additional pages on demand.
How it works:
The component maintains a repository name input.
useSWRInfiniteis used with a page key function that constructs the API URL based on the current page index.The hook returns data arrays for each page, which are concatenated to form a single list of issues.
Controls for loading more pages, refreshing data, and clearing results are provided.
Several loading and boundary states (e.g., "no more issues", "loading...") are handled to give user feedback.
Interaction with other parts
Uses a custom fetch utility (examples/infinite/libs/fetch.js) as the fetcher function for SWR.
Relies on SWR's internal cache and revalidation mechanisms for efficient data management.
React component state (
useState) is used to control user input and trigger data source changes.
Code snippet from examples/infinite/pages/index.js:
const { data, error, mutate, size, setSize, isValidating } = useSWRInfinite(
(index) =>
`https://api.github.com/repos/${repo}/issues?per_page=${PAGE_SIZE}&page=${index + 1}`,
fetch
)
const issues = data ? [].concat(...data) : []
2. Subscription Example
This example illustrates how to use useSWRSubscription to subscribe to an external event emitter, receiving real-time data updates and error notifications.
Core idea: Establish a subscription to an event source emitting data asynchronously, updating UI reactively.
How it works:
An
EventEmittersimulates an external data source emitting data every second.The subscription hook registers event listeners for "data" and "error" events.
It uses the SWR subscription middleware to invoke
nextcallbacks that update the React component's state.The subscription is properly cleaned up on component unmount to prevent memory leaks.
Errors emitted by the event source are captured and displayed.
Interaction with other parts
Integrates with SWR's subscription middleware internally to manage lifecycle and state updates.
Demonstrates the middleware architecture that extends SWR hooks for real-time use cases.
Uses React state updates triggered by subscription events for UI rendering.
Code snippet from examples/subscription/pages/index.js:
const { data, error } = useSWRSubscription('my-sub', (key, { next }) => {
event.on("data", (value) => next(undefined, value));
event.on("error", (err) => next(err));
start();
return () => {
stopped = true;
};
})
End-to-End (E2E) Testing Suite
The E2E tests are critical to maintaining the reliability of the SWR library across complex scenarios. They cover:
Rendering behaviors with Suspense and preloading.
Manual retry flows combined with React Error Boundaries.
Mutation sequences and status updates.
Infinite loading and concurrency handling.
Integration with server components supporting serialization.
Example E2E workflows
Suspense with Preload Test: Validates that preloading data avoids loading waterfalls and that the suspense fallback is correctly replaced with loaded content.
Retry in Suspense Tests: Confirm that errors caught by Suspense and Error Boundaries can be retried manually, triggering SWR's revalidation.
Mutation Test: Checks that mutation states (
isMutating) and resulting data updates reflect properly in the UI.Serialization Test: Ensures
unstable_serializeworks in server-side React components.
Interaction with other parts
These tests interact with example app pages and components that implement the SWR hooks with various configurations.
They use Playwright to simulate user interactions and assert UI state changes.
Help verify the correctness of internal SWR cache, revalidation logic, and middleware effects in integrated environments.
Code snippet from e2e/test/initial-render.test.ts:
test('should be able to retry in suspense with mutate', async ({ page }) => {
await page.goto('./suspense-retry-mutate', { waitUntil: 'commit' })
await expect(page.getByText('Something went wrong')).toBeVisible()
await page.getByRole('button', { name: 'retry' }).click()
await expect(page.getByText('data: SWR suspense retry works')).toBeVisible()
})
Module Workflow Visualization
The following flowchart illustrates the overall workflow of how example applications interact with SWR's core hooks and how E2E tests validate these interactions:
flowchart TD
A[Example React Component] --> B[Uses SWR Hook]
B --> C[Internal SWR Middleware & Cache Management]
C --> D[Data Fetching / Subscription Setup]
D --> E[API or External Data Source]
E -->|Data or Error| D
D -->|Update| C
C -->|Trigger Rerender| A
subgraph E2E Tests
T1[Test User Interaction]
T2[Assert UI State]
end
A --> T1
T1 --> B
T2 --> A
This diagram shows the cyclic nature of data flow from components through SWR internals to data sources and back, with E2E tests simulating user behavior and asserting expected UI changes.
Summary of File Relationships
File Path | Role |
|---|---|
Infinite scroll example using | |
Fetch utility used in infinite example | |
| Real-time subscription example using |
| E2E tests covering suspense, retry, preload |
E2E tests verifying mutation workflows |
These files illustrate and verify the practical use and robustness of SWR's advanced features.
This documentation explains the design intent, functionality, and interactions of the Examples and End-to-End Tests module, referencing key example code and tests to clarify how users can leverage and validate the SWR data fetching library in real-world scenarios.