Skip to content

Instantly share code, notes, and snippets.

@coryhouse
Created July 6, 2020 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coryhouse/0f8fb4f6c64cdc180c4eb01123972373 to your computer and use it in GitHub Desktop.
Save coryhouse/0f8fb4f6c64cdc180c4eb01123972373 to your computer and use it in GitHub Desktop.
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