Skip to content

Instantly share code, notes, and snippets.

@Keldrik
Last active November 12, 2018 03:25
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 Keldrik/df34a19a46e7586181cb0a2e4e97fa43 to your computer and use it in GitHub Desktop.
Save Keldrik/df34a19a46e7586181cb0a2e4e97fa43 to your computer and use it in GitHub Desktop.
React Hooks - Using useState and useEffect for a simple generic data fetch
import { useState, useEffect } from "react";
const useFetch = url => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(async () => {
const response = await fetch(url);
const data = await response.json();
const [item] = data.results;
setData(item);
setLoading(false);
}, []);
return { data, loading };
};
export default useFetch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment