Docs
Fetch config
Defaults

Setting default values

You can set the default value of a request by passing it in the default prop. This will be returned initially if no data exists:

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 default values for your requests from the root component of your app, pass them in the defaults prop of the FetchConfig component:

Before:

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>
  )
}
 
function MyMessages() {
  const { loading, data } = useFetch('/api/messages', {
    default: []
  })
 
  if (loading) return <p>Loading messages</p>
 
  return <div>{data.length} messages</div>
}
 
export default function App() {
  return (
    <div>
      <MyProfile />
      <MyMessages />
    </div>
  )
}

After:

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
      defaults={{
        'GET /api/profile': {
          value: {
            name: '',
            email: ''
          }
        },
        'GET /messages': {
          value: []
        }
      }}
    >
      <div>
        <MyProfile />
        <MyMessages />
      </div>
    </FetchConfig>
  )
}
💡

If a value already exists in cacheProvider, FetchConfig won't set a default value

Last updated on January 31, 2023