All hooks Reference
This is a complete reference of all hooks and utilities available in http-react.
Hooks
useBlob
Returns a Blob or object URL from the request response.
import { useBlob } from 'http-react'
function App() {
const { data } = useBlob('/logo.png', { objectURL: true })
return <img src={data} alt="Logo" />
}When objectURL is false or omitted, data will be a Blob object instead of a URL string.
useCode
Returns the HTTP status code of a request.
const statusCode = useCode('key')
return <p>Status: {statusCode}</p>useConfig
Returns the configuration of a request or the nearest FetchConfig.
const config = useConfig('key')
return <pre>{JSON.stringify(config, null, 2)}</pre>If no ID is provided, returns the configuration from the nearest FetchConfig component.
HTTP Method Hooks
Convenience hooks that work like useFetch but automatically set the HTTP method.
Learn more about HTTP methods in the MDN documentation (opens in a new tab).
useGET- Same asuseFetchwithmethod: 'GET'useHEADuseLINKuseUNLINKuseOPTIONSusePATCHusePOSTusePURGEusePUTuseDELETE
useData
Returns only the data from a request.
const data = useData('key')
return <p>Name: {data.name}</p>useError
Returns the error state of a request.
const error = useError('key')
if (error) return <p>An error occurred</p>useFetch
The primary hook for making HTTP requests. This is the default export.
See the complete API documentation for all available options.
useGql
Sends a GraphQL request.
import { gql, useGql } from 'http-react'
const myQuery = gql`
query {
profile {
name
}
}
`
function App() {
const { data, loading } = useGql(myQuery, {
default: {
profile: {
name: ''
}
}
})
if (loading) return <p>Loading...</p>
return <p>{data.data.profile.name}</p>
}useImperative
Returns an Axios-like object for making imperative HTTP requests. Includes configuration from the nearest FetchConfig.
import { useImperative } from 'http-react'
function App() {
const fetcher = useImperative()
useEffect(() => {
async function getInfo() {
const { data, error, config } = await fetcher.get('/info')
console.log(data)
}
getInfo()
}, [])
}useLoading
Returns the loading state of a request.
const loading = useLoading('key')
if (loading) return <p>Loading...</p>useMutate
Returns a function to mutate request data optimistically.
const mutateUser = useMutate('user')
const afterMutate = () => revalidate('user')
return (
<button
onClick={() =>
mutateUser(
(u) => ({
...u,
name: ''
}),
afterMutate
)
}
>
Update
</button>
)useRequestEnd
Returns the Date when a request completed.
const lastSync = useRequestEnd('key')
if (!lastSync) return <p>Waiting for sync...</p>
return <p>Last sync: {lastSync.toLocaleDateString()}</p>useRequestStart
Returns the Date when a request started.
const startup = useRequestStart('key')
if (!startup) return <p>Request hasn't been sent</p>
return <p>Started: {startup.toLocaleDateString()}</p>useResolve
Runs an effect when a request completes successfully.
useResolve('key', (data) => {
console.log('Data synced:', data)
})
useResolve('another-key', (data) => {
console.log('Another request synced:', data)
})useResponseTime
Returns the time taken to complete a request in milliseconds.
const responseTime = useResponseTime('key')
if (!responseTime) return <p>Loading...</p>
return <p>Loaded in {responseTime}ms</p>useText
Returns the response as plain text.
const data = useText('key')
return <p>{data}</p>useExpiration
Returns the expiration date of cached request data.
const expiration = useExpiration('key')
return <p>Expires: {expiration?.toLocaleTimeString()}</p>useHasData
Returns whether a request has data available.
const hasData = useHasData('key')
return <p>{hasData ? 'Data exists' : 'No data available'}</p>useDebounceFetch
Makes a request with debouncing to avoid excessive API calls.
const [q, setQ] = useState('')
const { data: results } = useDebounceFetch('/search', {
auto: q,
query: { q },
debounce: '2 sec' // Wait 2 seconds after changes before sending request
})Utility Functions
Helper functions used internally but available as exports.
hasBaseUrl
Checks if a string is a complete URL with HTTP/HTTPS protocol.
import { hasBaseUrl } from 'http-react'
hasBaseUrl('https://facebook.com') // true
hasBaseUrl('http://localhost:8000') // true
hasBaseUrl('netflix.com') // falseisDefined
Checks if a value is not undefined.
import { isDefined } from 'http-react'
isDefined(null) // true
isDefined('') // true
isDefined() // false
isDefined(undefined) // falseisFunction
Checks if a value is a function.
import { isFunction } from 'http-react'
isFunction(window.location.reload) // true
isFunction('') // false
isFunction(() => {}) // true
isFunction(function () {}) // truenotNull
Checks if a value is not null.
import { notNull } from 'http-react'
notNull({}) // true
notNull('') // true
notNull(0) // true
notNull(null) // false
notNull(document.getElementById('non-existent')) // falserevalidate
Forces requests to refetch if they're not currently loading.
import useFetch, { revalidate } from 'http-react'
function App() {
const { data } = useFetch('/api')
return (
<button onClick={() => revalidate('GET /api')}>
Refresh
</button>
)
}Revalidate multiple requests at once:
import useFetch, { revalidate } from 'http-react'
function App() {
useFetch('/api')
useFetch('/another')
useFetch('/other', { key: { name: 'Other' } })
return (
<button
onClick={() => {
revalidate([
'GET /api',
'GET /another',
{ name: 'Other' }
])
}}
>
Refresh All
</button>
)
}serialize
Serializes an object to a JSON string.
import { serialize } from 'http-react'
serialize({ name: 'dany' }, null, 2) // '{"name":"dany"}'setURLParams
Replaces URL parameters with actual values. This is type safe and parses the params from the URL string.
import { setURLParams } from 'http-react'
setURLParams('api/[path]/:id', { path: 'books', id: 10 })
// 'api/books/10'
setURLParams('https://api/[id]?photo=some-photo.png', { id: 24 })
// 'https://api/24?photo=some-photo.png'isFormData
Checks if a value is a FormData instance.
import { isFormData } from 'http-react'
isFormData({}) // false
isFormData(new FormData()) // truedefaultCache
The default cache implementation used by http-react for storing request data.
mutateData
Mutates request data outside of React components. Useful for optimistic UI updates.
import { mutateData } from 'http-react'
// Mutate without revalidation
function onlyMutate() {
mutateData([
'GET /profile',
(prev) => ({
...prev,
name: 'new name'
})
])
}
// Mutate with revalidation
function mutateAndRevalidate() {
mutateData([
'GET /profile',
(prev) => ({
...prev,
name: 'new name'
}),
true // Revalidate after mutation
])
}
// Mutate multiple requests
function mutateMany() {
mutateData(
[
'GET /profile',
(prev) => ({ ...prev, name: 'new name' }),
true
],
[
'GET /post',
{ title: '' },
true
],
[
{ this_id: 'is_an_object' },
{ title: 'New title' },
true
]
)
}queryProvider
Creates a typed GraphQL client. See the GraphQL documentation for details.