Async initial state?
td0m opened this issue · comments
Dominik Tarnowski commented
Is there any way of setting an initial value that is fetched asynchronously?
Jamie Kyle commented
You could do something along the lines of this:
function useValue(initialState = () => null) {
let [value, setValue] = useState(null)
useEffect(() => {
Promise.resolve(initialState())
.then(initState => setCount(count))
.catch(err => ...)
}, [])
// ...
return { value }
}
Dominik Tarnowski commented
Thanks, this worked perfectly 👍
Les Szklanny commented
This tip should be added to the doc
Jamie Kyle commented
I don't want to bloat the documentation too much, these issues are a great place to search for specific use cases
ardeaf commented
Trying to use this pattern, I'm very unfamiliar with custom hooks and a newcomer to the library. Would this result in any race conditions? I keep reading that async stuff in useEffect can result in race conditions.