Docs
Fetch config
FetchConfig

FetchConfig

The FetchConfig component is used to set global properties that will be used by useFetch in any descendant component, like SSR, value (fallback), an more.

Keep in mind that you can still configure individual requests.

Wrap your app with the FetchConfig component:

import { FetchConfig } from 'http-react'
 
export default function App({ children }) {
  return (
    <FetchConfig
      headers={{
        Authorization: 'my-token'
      }}
      value={{
        'GET /todos': []
      }}
    >
      {children}
    </FetchConfig>
  )
}

With the configuration above, every useFetch call under that react tree will send the same Authorization header. However, this can be changed per request or by using FetchConfig somewhere else:

import useFetch, { FetchConfig } from 'http-react'
 
import LegacyComponent from '@components/legacy'
import NewComponent from '@components/new'
 
export default function App() {
  return (
    <div>
      <FetchConfig
        baseUrl='/api/v1'
        headers={{
          Authorization: 'Old token'
        }}
      >
        <LegacyComponent />
      </FetchConfig>
      <FetchConfig
        baseUrl='/api/v2'
        headers={{
          Authorization: 'New token'
        }}
      >
        <NewComponent />
      </FetchConfig>
    </div>
  )
}

You can also change how data is stored. For example, by using storage, provided by atomic-state:

import { FetchConfig } from 'http-react'
import { storage } from 'atomic-state'
 
export default function App({ children }) {
  return (
    <div>
      <FetchConfig baseUrl='/api' cacheProvider={storage}>
        {children}
      </FetchConfig>
    </div>
  )
}

You can also make useFetch revalidate when the window is focused again:

import { FetchConfig } from 'http-react'
 
export default function App({ children }) {
  return (
    <div>
      <FetchConfig revalidateOnFocus revalidateOnMount={false}>
        {children}
      </FetchConfig>
    </div>
  )
}

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

Learn more about revalidateOnMount