Docs
Fetch config
Fallback data

Fallback data

You can set the fallback value of a request by passing it in the default prop. This will be used as the initial data:

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>
  )
}

If you want to set fallback values from the root component of your app, pass them in the value prop of the FetchConfig component:

import useFetch, { FetchConfig } from 'http-react'
 
export default function Profile() {
  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 /messages': []
      }}
    >
      <div>
        <MyProfile />
        <MyMessages />
      </div>
    </FetchConfig>
  )
}

If you are using server components you can pass promises as fallback values (keep in mind that this works only in server components):

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() // No await needed!
      }}
    >
      <div>{children}</div>
    </FetchConfig>
  )
}

Then in your client component:

'use client'
 
import useFetch from 'http-react'
 
export default function Todos() {
  const { data } = useFetch('/todos', {
    id: 'todos' // This will replace 'GET /todos' for 'todos' as the request id
  })
 
  return (
    <div>
      <h2>Total todos: {data.length}</h2>
    </div>
  )
}