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:

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'

Variables and Constants

let count = 0
const key = 'manual-retry-18-2'

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

Returns

Behavior

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

Returns

Special Options

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

Returns

Usage Example

// e.g., call this before rendering the component that uses useRemoteData
preloadRemote().then(() => {
  console.log('Data preloaded')
})

Implementation Details and Algorithms


Interaction with Other System Parts


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:


Summary

Export

Type

Description

fetcher

() => Promise<string>

Fetches remote data with simulated retry error on first call.

useRemoteData

() => SWRResponse

React hook to access remote data using SWR with suspense.

preloadRemote

() => Promise<void>

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