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


Variables and Constants


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

Parameters

Returns

Usage Example

fetcher()
  .then(name => console.log(name))
  .catch(error => console.error(error))

Hook: useRemoteData

export const useRemoteData = () =>
  useSWR(key, fetcher, {
    suspense: true
  })

Description

Parameters

Returns

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

Parameters

Returns

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


Interaction with Other Parts of the System


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.