Created
July 6, 2020 15:12
-
-
Save coryhouse/0f8fb4f6c64cdc180c4eb01123972373 to your computer and use it in GitHub Desktop.
This file contains 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 { useState, useEffect, useRef } from "react"; | |
// This custom hook centralizes and streamlines handling of HTTP calls | |
export default function useFetch(url, init) { | |
const [data, setData] = useState(null); | |
const [loading, setLoading] = useState(true); | |
const [error, setError] = useState(null); | |
const prevInit = useRef(); | |
const prevUrl = useRef(); | |
useEffect(() => { | |
// Only refetch if url or init params change. | |
if (prevUrl.current === url && prevInit.current === init) return; | |
prevUrl.current = url; | |
prevInit.current = init; | |
fetch(process.env.REACT_APP_API_BASE_URL + url, init) | |
.then(response => { | |
if (response.ok) return response.json(); | |
setError(response); | |
}) | |
.then(data => setData(data)) | |
.catch(err => { | |
console.error(err); | |
setError(err); | |
}) | |
.finally(() => setLoading(false)); | |
}, [init, url]); | |
return { data, loading, error }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment