Reusing requests
If you want to use the same request in multiple places in your app, you can do so. Internally, http-react
knows the current state of requests that were initialized by useFetch
, whether they are loading, they completed succesfuly or failed, while preventing duplicated requests. This information is shared between any subscribers that use useFetch
or any of its forms (useData
, useLoading
, etc).
import useFetch from 'http-react'
// First, create a custom hook that returns the user info.
// You can pass any other configuration you want to send in
// the request (e.g. 'keepalive', 'cache', 'method')
function useUserInfo() {
return useFetch('/api/user-info', {
headers: {
Authorization: 'my-token'
},
cache: 'only-if-cached',
mode: 'cors'
})
}
You can use the useUserInfo
function in any component or hook:
function UserInfo() {
const { data, loading, error } = useUserInfo()
if (loading) return <p>Loading</p>
if (error) return <p>An error ocurred</p>
return (
<div>
<p>Username: {data.name}</p>
</div>
)
}
function AccountBalance() {
const { data, loading, error } = useUserInfo()
if (loading) return <p>Loading account balance</p>
if (error) return <p>Unable to get account balance</p>
return (
<div>
<p>Balance: {data.accountBalance}</p>
</div>
)
}
export default function Page() {
return (
<div>
<UserInfo />
<AccountBalance />
</div>
)
}
The cool thing about it is that even though the useUserInfo
hook is used in two places only one request will be sent (See Data deduplication (opens in a new tab)) and every subscriber using it will update when the state of the request changes.