Created
June 2, 2023 21:50
-
-
Save ValentaTomas/d3f0b08bbf0d909894384d5511c82562 to your computer and use it in GitHub Desktop.
Simple wrapper for useEffect and useState hook to execute and store results of async operations.
This file contains 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
import { useEffect, useState } from 'react' | |
export function useAsyncResource<T>(fetchResource: () => Promise<T>) { | |
const [data, setData] = useState<T>() | |
const [error, setError] = useState<any>() | |
useEffect(function getResource() { | |
fetchResource() | |
.then(setData) | |
.catch(setError) | |
}, [fetchResource]) | |
return { | |
data, | |
error, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment