Last active
September 25, 2025 19:42
-
-
Save ntatko/4bae7b3efee0f5385e5500c73d168b63 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
| // Reusable fetching hook | |
| const useRequest = (requestFunc) => { | |
| const [data, setData] = useState({}) | |
| const [loading, setLoading] = useState(false) | |
| const [error, setError] = useState(null) | |
| const fetch = async () => { | |
| setLoading(true) | |
| try { | |
| const data = await requestFunc() | |
| setData(data) | |
| } catch (e) { | |
| setError(e) | |
| } finally { | |
| setLoading(false) | |
| } | |
| }) | |
| useEffect(() => { | |
| fetch() | |
| }, [fetch, requestFunc]) | |
| return {data, loading, error, refetch: fetch} | |
| } | |
| // Your react component | |
| const Component = ({ id }) => { | |
| const { data, loading, error, refetch } = useRequest( | |
| () => fetch(`/data/${id}`) | |
| ) | |
| const [state, setState] = useState(null) | |
| useEffect(() => { | |
| refetch() | |
| }, [state]) | |
| if (error) return <ErrorScreen /> | |
| if (loading) return <Spinner /> | |
| return <>{data.property}</> | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why do you have the code wrapped in an IIFE inside the function passed to useEffect?