use-remote-data.ts
Overview
The use-remote-data.ts file is a lightweight utility module designed to handle remote data fetching within a React environment using the SWR (stale-while-revalidate) library. It provides a custom React hook useRemoteData that internally manages data retrieval from a remote API endpoint (/api/retry) with built-in retry logic and error handling. Additionally, it exports a preloadRemote function to prefetch and cache the data before the component mounts, improving perceived performance.
This file leverages SWR's suspense mode to integrate seamlessly with React's Suspense mechanism, enabling declarative data fetching and error handling in UI components.
Detailed Explanation
Imports
useSWRandpreloadare imported from the swr library.useSWRis a React hook for data fetching with automatic caching, revalidation, focus tracking, and more.preloadis used to prefetch and cache data for a given key and fetcher function.
Variables and Constants
count(number): A simple counter that tracks how many times thefetcherfunction has been invoked. It is used to simulate a failure on the first fetch attempt.key(string): A unique cache key'manual-retry-18-3'used by SWR to identify and store the fetched data.
Function: fetcher
const fetcher = () => {
count++
if (count === 1) return Promise.reject('wrong')
return fetch('/api/retry')
.then(r => r.json())
.then(r => r.name)
}
Description
The
fetcherfunction is responsible for fetching data from the remote API endpoint/api/retry.It increments the
countvariable each time it is called.On the first invocation (
count === 1), it intentionally rejects with the error"wrong"to simulate a failure scenario.On subsequent calls, it performs a fetch request to
/api/retry, parses the JSON response, and returns thenameproperty from the response object.
Parameters
None.
Returns
A Promise that resolves to a
string(thenamefield from the API response) or rejects with an error message on the first call.
Usage Example
fetcher()
.then(name => console.log(name))
.catch(error => console.error(error))
Hook: useRemoteData
export const useRemoteData = () =>
useSWR(key, fetcher, {
suspense: true
})
Description
useRemoteDatais a custom React hook wrapping SWR'suseSWRhook.It uses the predefined
keyandfetcherfor data retrieval.Enables
suspense: truemode, allowing React Suspense to handle loading and error states declaratively.Returns SWR's response object, which includes properties like
data,error,isLoading,mutate, etc.
Parameters
None.
Returns
An object representing the SWR response, typically:
data: The fetchednamestring on success.error: Any error thrown during fetching.Other SWR-related utilities.
Usage Example
import { useRemoteData } from './use-remote-data'
function MyComponent() {
const { data, error } = useRemoteData()
if (error) return <div>Error: {error.toString()}</div>
if (!data) return <div>Loading...</div>
return <div>Fetched name: {data}</div>
}
Note: When using
suspense: true, the component should be wrapped in a React<Suspense>boundary to handle the loading state.
Function: preloadRemote
export const preloadRemote = () => preload(key, fetcher)
Description
Triggers preloading of remote data by invoking SWR's
preloadfunction with the samekeyandfetcher.This primes the cache ahead of time, allowing components that use
useRemoteDatato access the data immediately without waiting for the fetch.
Parameters
None.
Returns
A Promise that resolves when the preloading is complete.
Usage Example
import { preloadRemote } from './use-remote-data'
// Call this early, e.g., on page load or navigation
preloadRemote().then(() => {
console.log('Data preloaded')
})
Important Implementation Details and Algorithms
Retry Simulation: The
fetcherfunction intentionally rejects the first call to simulate a failure, which triggers SWR's retry mechanism. On subsequent calls, it fetches data normally.SWR Suspense Integration: Using
suspense: trueallows React Suspense to handle the loading and error states, enabling cleaner components that do not need explicit loading or error checks.Cache Key: The cache key
'manual-retry-18-3'uniquely identifies this data fetch in SWR's global cache to avoid clashes with other data.
Interaction with Other Parts of the System
API Endpoint: This file depends on a backend API at
/api/retrywhich returns a JSON object containing anamefield.UI Components: Components import and use
useRemoteDatato fetch and display remote data reactively.Preloading: The
preloadRemotefunction is intended to be used in routing logic or higher-level components to warm up the cache before rendering.SWR Cache: Interacts with SWR’s global cache to store and manage the fetched data and its states.
Visual Diagram
flowchart TD
A[useRemoteData] -->|calls| B[useSWR(key, fetcher, suspense: true)]
C[preloadRemote] -->|calls| D[preload(key, fetcher)]
B -->|uses| E[fetcher function]
D -->|uses| E
E -->|on first call| F[Reject Promise with "wrong"]
E -->|on subsequent calls| G[fetch('/api/retry')]
G --> H[Parse JSON]
H --> I[Return r.name]
style A fill:#f9f,stroke:#333,stroke-width:2px
style C fill:#f9f,stroke:#333,stroke-width:2px
Summary
use-remote-data.ts is a concise utility module that provides React components with a robust, suspense-enabled data fetching hook and preloading capability using SWR. It simulates a retry scenario to demonstrate error handling and integrates tightly with the API endpoint /api/retry. This file plays a key role in managing remote asynchronous data in a declarative and efficient manner within the application.