use-remote-data.ts
Overview
use-remote-data.ts is a utility module designed to facilitate fetching and managing remote data in a React application using the swr (stale-while-revalidate) library. It provides:
A custom data fetching function (
fetcher) with built-in retry behavior simulation.A React hook (
useRemoteData) to easily consume the remote data with React Suspense support.A preload function (
preloadRemote) to prefetch and cache the data ahead of usage for performance optimization.
This module abstracts the complexities of remote data fetching, error handling, and caching, enabling components to declaratively access remote data with minimal boilerplate.
Detailed Explanation
Imports
import useSWR from 'swr'
import { preload } from 'swr'
Imports the main
useSWRhook and thepreloadfunction from theswrlibrary.useSWRmanages data fetching, caching, revalidation, and error handling.preloadallows prefetching data outside a component lifecycle.
Variables and Constants
let count = 0
const key = 'manual-retry-18-2'
count(module-scoped variable) tracks how many times thefetcherhas been invoked.keyis the unique cache key used byswrto identify the remote data.
Function: fetcher
export const fetcher = () => {
count++
if (count === 1) return Promise.reject('wrong')
return fetch('/api/retry')
.then(r => r.json())
.then(r => r.name)
}
Purpose
fetcher is an asynchronous function responsible for fetching remote data from the /api/retry endpoint and returning a processed result. It simulates a failure on the first call to demonstrate retry or error handling behavior.
Parameters
None.
Returns
A
Promise<string>resolving to thenameproperty from the JSON response.On the first invocation, it rejects the promise with the error string
'wrong'to simulate a fetch failure.
Behavior
Increments
counton each call.If
countis1, immediately rejects.Otherwise, performs a
fetchrequest to/api/retry.Parses the JSON response and returns the
namefield.
Usage Example
fetcher()
.then(name => console.log(name))
.catch(err => console.error(err))
This function can be used standalone or by hooks like useSWR for data fetching.
Hook: useRemoteData
export const useRemoteData = () =>
useSWR(key, fetcher, {
suspense: true
})
Purpose
useRemoteData is a custom React hook that wraps the useSWR hook, binding it to a specific cache key and fetcher function to retrieve remote data.
Parameters
None.
Returns
Returns the SWR response object, which includes:
data: The fetched data (string | undefined).error: Any error encountered during fetching.isValidating: Boolean indicating if the data is being revalidated.Other SWR utilities.
Special Options
suspense: trueenables React Suspense mode, making the hook throw a Promise during loading for Suspense boundary handling.
Usage Example
import React, { Suspense } from 'react'
import { useRemoteData } from './use-remote-data'
function MyComponent() {
const { data } = useRemoteData()
return <div>Remote Name: {data}</div>
}
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
)
}
Function: preloadRemote
export const preloadRemote = () => preload(key, fetcher)
Purpose
preloadRemote triggers a prefetch of the remote data and caches it under the same key used by useRemoteData. This function is useful to warm up the cache before components mount.
Parameters
None.
Returns
Returns a
Promiseresolving when the data has been fetched and cached.
Usage Example
// e.g., call this before rendering the component that uses useRemoteData
preloadRemote().then(() => {
console.log('Data preloaded')
})
Implementation Details and Algorithms
Simulated Retry Behavior: The
fetcherfunction fails intentionally on its first call (count === 1) by rejecting the Promise. This simulates a transient failure scenario where the first fetch might fail, and subsequent retries succeed. This is useful for testing error boundaries, retry logic, or demonstrating SWR's automatic revalidation and error recovery capabilities.Use of SWR Suspense: By enabling
suspense: truein the SWR options, the hook integrates with React Suspense, which simplifies asynchronous component loading states by letting components "throw" a Promise until data is ready.Cache Key Management: The unique string
manual-retry-18-2serves as a cache key to identify the data in SWR's cache. This ensures that both the hook and the preload function refer to the same cache entry.Preloading: The
preloadfunction from SWR is used to fetch data and prime the cache without binding it to a React component lifecycle. This can improve perceived performance by loading data ahead of time.
Interaction with Other System Parts
API Endpoint
/api/retry: This file depends on the backend API endpoint/api/retryto fetch JSON data. The endpoint must return a JSON object with anameproperty, e.g.,{ "name": "example" }.React Components: Components import
useRemoteDatato access the remote data reactively, benefiting from SWR's caching and revalidation features. Components must be wrapped in a Suspense boundary when usinguseRemoteDatadue to thesuspense: trueoption.Preloading Workflow: Other parts of the application can call
preloadRemoteto initiate data fetching before components mount, enabling smoother UI transitions and reducing load times.
Mermaid Flowchart: Function Relationships and Data Flow
flowchart TD
A[Component uses useRemoteData] -->|calls| B[useSWR with key + fetcher]
B -->|calls on cache miss| C[fetcher()]
C -->|count++| D{Is count === 1?}
D -->|Yes| E[Reject Promise with "wrong"]
D -->|No| F[Fetch /api/retry]
F --> G[Parse JSON response]
G --> H[Return r.name]
E & H --> I[useSWR caches result]
I --> A
J[preloadRemote()] -->|calls| B
Diagram Explanation:
The main hook
useRemoteDatainternally callsuseSWRwith a fixed key and thefetcher.On cache miss,
useSWRinvokesfetcher.fetcherincrementscountand simulates failure on the first call.Subsequent calls fetch data from
/api/retry.The fetched result or error is cached and returned to the component.
preloadRemoteshares the same flow to prefetch and cache data.
Summary
Export | Type | Description |
|---|---|---|
|
| Fetches remote data with simulated retry error on first call. |
| React hook to access remote data using SWR with suspense. | |
|
| Prefetches and caches remote data using SWR's preload utility. |
This file encapsulates remote data fetching logic, error simulation, and caching strategies to provide resilient and performant data consumption in React apps using SWR. It is designed to integrate seamlessly with components and backend APIs, supporting advanced features like Suspense and preloading.
End of documentation for use-remote-data.ts