I wrote this little hook so I could fetch some remote resources:
import {DependencyList, useEffect, useRef, useState} from "react";
export default function useAsyncValue<T>(cb: () => Promise<T>, deps?: DependencyList): T | undefined {
const [value, setValue] = useState<T | undefined>(undefined)
const nonce = useRef(Symbol())
useEffect(() => {
const current = nonce.current = Symbol()
Promise.resolve(cb()).then(result => {
if (nonce.current === current) {
setValue(result)
}
})
return () => {
nonce.current = Symbol()
}
}, deps)
return value
}
Use is like:
const value = useAsyncValue(() => fetch("..."))
I added a nonce and some deps too so if you do:
const value = useAsyncValue(() => fetch(`/get?foo=${foo}`), [foo])
Then you value will always be the latest result, and you won't have any results out-of-order bugs from older fetch returning after a later fetch.
Are there any problems with this? I don't need to pass the counter into the useEffects deps list do I?