jamiebuilds / unstated-next

200 bytes to never think about React state management libraries ever again

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Async initial state?

td0m opened this issue · comments

Is there any way of setting an initial value that is fetched asynchronously?

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 }
}

Thanks, this worked perfectly 👍

This tip should be added to the doc

I don't want to bloat the documentation too much, these issues are a great place to search for specific use cases

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.