Last active
August 8, 2021 03:18
-
-
Save cant89/8d8594e2595f5194d58cc0daea896c22 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const useFetch = (service) => { | |
const [loading, setLoading] = useState(true); | |
const [error, setError] = useState(); | |
const [data, setData] = useState(); | |
const fetchAPI = useCallback(async () => { | |
try { | |
const res = await fetch(service); | |
const json = await res.json(); | |
setData(json); | |
} catch (err) { | |
setError(err); | |
} | |
setLoading(false); | |
}, [service]); | |
useEffect(() => { | |
fetchAPI(); | |
}, [fetchAPI]); | |
return { data, error, loading }; | |
}; | |
const Todo = () => { | |
const { data, error, loading } = useFetch( | |
"https://jsonplaceholder.typicode.com/todos/1" | |
); | |
useEffect(() => { | |
// eventually dispatch redux action | |
// if you need to store something | |
}, [data]); | |
if (error) { | |
return `Error: ${error} `; | |
} | |
if (loading) { | |
return "Loading..."; | |
} | |
if (data) { | |
const { title, completed } = data; | |
return `${title} is ${!completed && "not "} completed`; | |
} | |
return null; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment