Getting started
Installation
Using yarn
yarn add http-react
Or with npm
npm install --save http-react
Quick start
Basic example
fetcher
(optional)
Create a fetcher
function that will fetch your data
// This is the default fetcher
const fetcher = (url, config) => fetch(url, config)
You can use your favorite fetching library, like axios:
import axios from 'axios'
const fetcher = (url, config) => axios(url, config)
Your fetcher
function must return an object with the data
and status
properties. You can replace data
with a json
method that returns the data
You can start using useFetch
right away:
import useFetch from 'http-react'
export default function App() {
const { data, isPending, error, responseTime } = useFetch('/api/user-info', {
refresh: '30 sec', // Refresh profile every 30 seconds
fetcher
})
if (isPending) return <p>Loading</p>
if (error) return <p>An error ocurred</p>
return (
<div>
<h2>Welcome, {data.name}</h2>
<small>Profile loaded in {responseTime} miliseconds</small>
</div>
)
}
The first argument passed to useFetch
is the input of the request; it can be a URL or a Request
object.
By default, the URL this will be used along with the method
to create a unique id to do things like deduplication and sync the state of a request between hook calls. (in this example, the id will be GET /api/user-info
)
The second argument is the request configuration. This configuration accepts everything that fetch
accepts and more. In this example, refresh
tells useFetch
to revalidate again 30 seconds after the initial and any subsequent request completes. refresh
is not part of the native fetch
configuration, it's one of the many features provided by http-react
.
Optional
Wrap your app with the FetchConfig
component.
You can use it to set global configurations like cache, headers, default (fallback) values for certain requests, configure which requests will trigger Suspense
(opens in a new tab), etc. It can also be used for SSR and works inside Server Components (opens in a new tab)
import { FetchConfig } from 'http-react'
export default function App() {
return (
<FetchConfig
baseUrl='/api'
refresh={30}
headers={{ Authorization: 'Token' }}
value={{
'GET /todos': [] // fallback for `useFetch('/todos')`
}}
>
<div>
<h2>My app</h2>
</div>
</FetchConfig>
)
}