Created
April 3, 2023 03:56
-
-
Save jhavenz/9bf2bc32b61f266b5c5e4784876e18ff to your computer and use it in GitHub Desktop.
useFetch React Hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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