Docs
Fetch config
Fallback data

Fallback Data

Fallback data provides initial values for your requests, preventing undefined states and improving the user experience during loading.

Component-Level Fallback

Set fallback data directly in useFetch using the default option:

import useFetch from 'http-react'
 
export default function Profile() {
  const { data } = useFetch('/api/profile', {
    default: {
      name: 'Loading name...',
      email: 'Loading email...'
    }
  })
 
  return (
    <section>
      <p>Name: {data.name}</p>
      <p>Email: {data.email}</p>
    </section>
  )
}

The fallback data is used immediately while the request is in progress.

Global Fallback with FetchConfig

Set fallback values for multiple requests at the app level using the value prop in FetchConfig:

import useFetch, { FetchConfig } from 'http-react'
 
function MyProfile() {
  const { data } = useFetch('/api/profile')
 
  return (
    <section>
      <p>Name: {data.name}</p>
      <p>Email: {data.email}</p>
    </section>
  )
}
 
function MyMessages() {
  const { loading, data } = useFetch('/api/messages')
 
  if (loading) return <p>Loading messages...</p>
 
  return <div>{data.length} messages</div>
}
 
export default function App() {
  return (
    <FetchConfig
      value={{
        'GET /api/profile': {
          name: '',
          email: ''
        },
        'GET /api/messages': []
      }}
    >
      <div>
        <MyProfile />
        <MyMessages />
      </div>
    </FetchConfig>
  )
}

The keys in the value object should match the request Key format (e.g., 'GET /api/profile').

Server Component Integration

In React Server Components, you can pass promises as fallback values without awaiting them:

import { FetchConfig } from 'http-react'
 
function getTodos() {
  return fetch('https://api.com/todos').then((res) => res.json())
}
 
export function MyServerComponent({ children }) {
  return (
    <FetchConfig
      value={{
        todos: getTodos() // Promise is passed directly
      }}
    >
      <div>{children}</div>
    </FetchConfig>
  )
}

Access the resolved data in your client component using a custom request ID:

'use client'
 
import useFetch from 'http-react'
 
export default function Todos() {
  const { data } = useFetch('/todos', {
    key: 'todos' // Matches the key in FetchConfig
  })
 
  return (
    <div>
      <h2>Total todos: {data.length}</h2>
    </div>
  )
}

This pattern enables efficient server-side data fetching with seamless client-side hydration.