Skip to content

Instantly share code, notes, and snippets.

@Dromediansk
Created April 8, 2020 02:59
Show Gist options
  • Save Dromediansk/a308da027d4e0daedb032df98b89a7bc to your computer and use it in GitHub Desktop.
Save Dromediansk/a308da027d4e0daedb032df98b89a7bc to your computer and use it in GitHub Desktop.
fetching data custom hook final version
import { useState, useEffect } from "react";
export const useFetch = (url, ref, initialValue) => {
const [data, setData] = useState(initialValue);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
if (ref.current) {
(async () => {
try {
const res = await fetch(url);
const resJson = await res.json();
setData(resJson);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
})();
}
return () => {
ref.current = false;
};
}, [url, ref]);
return { loading, data, error };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment