🐶 React hook for making isomorphic http requests
Need to fetch some data? Try this one out. It's an isomorphic fetch hook. That means it works with SSR (server side rendering).yarn add use-httpimport useFetch from 'use-http'
function App() {
// add whatever other options you would add to `fetch` such as headers
const options = {
method: 'POST',
body: {}, // whatever data you want to send
}
var [data, loading, error] = useFetch('https://example.com', options)
// want to use object destructuring? You can do that too like:
var { data, loading, error } = useFetch('https://example.com', options)
if (error) {
return 'Error!'
}
if (loading) {
return 'Loading!'
}
return (
<code>
<pre>{data}</pre>
</code>
)
}Or you can use one of the nice helper hooks. All of them accept the second options parameter.
import { useGet, usePost, usePatch, usePut, useDelete } from 'use-http'
function App() {
const [data, loading, error] = useGet('https://example.com')
if (error) {
return 'Error!'
}
if (loading) {
return 'Loading!'
}
return (
<code>
<pre>{data}</pre>
</code>
)
}| Option | Description |
|---|---|
useFetch |
The base hook |
useGet |
Defaults to a GET request |
usePost |
Defaults to a POST request |
usePut |
Defaults to a PUT request |
usePatch |
Defaults to a PATCH request |
useDelete |
Defaults to a DELETE request |
| Option | Description |
|---|---|
options |
This is exactly what you would pass to the normal js fetch |
- Make abortable (add
abortto abort the http request) - Make work with React Suspense
- Allow option to fetch on server instead of just having
loadingstate - Allow option for callback for response.json() vs response.text()
- Add a
refetchoption - Potentially add syntax like
useFetch({ url: '', method: '' })
