Skip to content

Instantly share code, notes, and snippets.

@hitrik
Last active March 26, 2019 09:48
Show Gist options
  • Save hitrik/0e2db747fbe50f2880c2c08ef9b5a405 to your computer and use it in GitHub Desktop.
Save hitrik/0e2db747fbe50f2880c2c08ef9b5a405 to your computer and use it in GitHub Desktop.
//Reactjs custom hook
export const useFetch = ({ url, ...options = {} }) => {
let [data, setData] = useState(null);
const [error, setError] = useState(null);
const [status, setStatus] = useState(null);
const [loading, setLoading] = useState(true);
const ref = useRef();
useEffect(
() => {
const processData = async () => {
const response = await window.fetch(url, (options));
data = await response.json();
setData(data);
setStatus(response.status);
setLoading(false);
};
processData().catch((error) => {
setError(error);
setLoading(false);
});
},
[ref]
);
return [data, error, status, loading];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment