Skip to content

Instantly share code, notes, and snippets.

@Vikaskumargd
Forked from Dromediansk/useFetch.js
Created April 9, 2020 21:53
Show Gist options
  • Save Vikaskumargd/1afdd1d4487d97f3f58d4ce72c1735a3 to your computer and use it in GitHub Desktop.
Save Vikaskumargd/1afdd1d4487d97f3f58d4ce72c1735a3 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