Skip to content

Instantly share code, notes, and snippets.

@jhavenz
Created April 3, 2023 03:56
Show Gist options
  • Save jhavenz/9bf2bc32b61f266b5c5e4784876e18ff to your computer and use it in GitHub Desktop.
Save jhavenz/9bf2bc32b61f266b5c5e4784876e18ff to your computer and use it in GitHub Desktop.
useFetch React Hook
import useAsync from '@/hooks/useAsync/useAsync'
import React from 'react'
const DEFAULT_OPTIONS = {
headers: { 'Content-Type': 'application/json' },
}
export default function useFetch(url, options = {}, dependencies = []) {
return useAsync(() => {
return fetch(url, { ...DEFAULT_OPTIONS, ...options }).then((res) => {
if (res.ok) return res.json()
return res.json().then((json) => Promise.reject(json))
})
}, dependencies)
}
import useFetch from '@/hooks/useFetch/useFetch'
import React, { useState } from 'react'
export default function UseFetchExampleComponent() {
const [id, setId] = useState(1)
const { loading, error, value } = useFetch(
`https://jsonplaceholder.typicode.com/todos/${id}`,
{},
[id]
)
return (
<div>
<div>{id}</div>
<button onClick={() => setId((currentId) => currentId + 1)}>
Increment ID
</button>
<div>Loading: {loading.toString()}</div>
<div>{JSON.stringify(error, null, 2)}</div>
<div>{JSON.stringify(value, null, 2)}</div>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment