Skip to content

Instantly share code, notes, and snippets.

@IgnacioCastro0713
Created June 17, 2020 03:26
Show Gist options
  • Save IgnacioCastro0713/f85264deae34e924da46502423c628fa to your computer and use it in GitHub Desktop.
Save IgnacioCastro0713/f85264deae34e924da46502423c628fa to your computer and use it in GitHub Desktop.
hook http fetch
import { useState, useEffect } from 'react';
export default function useFetch(url, options) {
const [loading, setLoading] = useState(true);
const [result, setResult] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
(async () => {
try {
const result = await fetch(url, options);
const json = await result.json();
setResult(json);
setLoading(false)
} catch (error) {
setError(error);
setLoading(false)
}
})();
}, [url, options]);
return { loading, result, error };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment