Rajasekar Thangavel Posted on May 23, 2022 • Edited on Dec 2, 2022 1 1 Create custom fetch hook in react #customhook #react Custom hook useFetch import { useState, useEffect } from 'react'; const useFetch = (url, initialValue) => { const [data, setData] = useState(initialValue); const [error, setError] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { (async () => { try { const res = await fetch(url); const resJson = await res.json(); setData(resJson); } catch (err) { setError(err); } finally { setLoading(false); } })(); }, [url]); return { loading, data, error }; }; export default useFetch; Enter fullscreen mode Exit fullscreen mode usage import useFetch from "./useFetch"; const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/todos', []); Enter fullscreen mode Exit fullscreen mode Sentry Promoted Dropdown menu What's a billboard? Manage preferences Report billboard If seeing this in React makes you 🤮, get Sentry. Try Sentry Top comments (0) Subscribe Personal Trusted User Create template Templates let you quickly answer FAQs or store snippets for re-use. Submit Preview Dismiss Code of Conduct • Report abuse Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well Confirm For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)