Skip to content

Instantly share code, notes, and snippets.

@ValentaTomas
Created June 2, 2023 21:50
Show Gist options
  • Save ValentaTomas/d3f0b08bbf0d909894384d5511c82562 to your computer and use it in GitHub Desktop.
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.
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