useRecoilStateLoadable(state)
This hook is intended to be used for reading the value of asynchronous selectors. This hook will implicitly subscribe the component to the given state.
Unlike useRecoilState()
, this hook will not throw an Error
or Promise
when reading from an asynchronous selector (for the purpose of working alongside React Suspense). Instead, this hook returns a Loadable
object for the value along with the setter callback.
function useRecoilStateLoadable<T>(state: RecoilState<T>): [Loadable<T>, (T | (T => T)) => void]
state
: a writeableatom
orselector
that may have some asynchronous operations. The status of the returned loadable will depend on the status of the provided state selector.
Returns a Loadable
for the current state with the interface:
state
: indicates the status of the selector. Possible values are'hasValue'
,'hasError'
,'loading'
.contents
: The value represented by thisLoadable
. If the state ishasValue
, it is the actual value, if the state ishasError
it is theError
object that was thrown, and if the state isloading
, then it is aPromise
of the value.
Example
function UserInfo({userID}) {
const [userNameLoadable, setUserName] = useRecoilStateLoadable(userNameQuery(userID));
switch (userNameLoadable.state) {
case 'hasValue':
return <div>{userNameLoadable.contents}</div>;
case 'loading':
return <div>Loading...</div>;
case 'hasError':
throw userNameLoadable.contents;
}
}