A Loadable is a value type that represents the state of an asynchronous operation. It is used to encapsulate whether a value is currently loading, has successfully loaded, or has encountered an error. Because Loadable is a value type, it is immutable; when the underlying request status changes, a new Loadable instance is created rather than mutating the existing one.
A Loadable can be in one of three states:
hasValue (ValueLoadable): The operation completed successfully. Use getValue() or valueMaybe() to access the data.loading (LoadingLoadable): The operation is in progress. Use promiseMaybe() or toPromise() to access the pending Promise.hasError (ErrorLoadable): The operation failed. Use errorMaybe() or errorOrThrow() to access the error object.
You can transform a Loadable using the .map() method, which allows you to apply a function to the underlying value. If the mapping function returns a Promise, a new LoadingLoadable is returned; if it returns a new Loadable, that state is preserved.
import { RecoilLoadable } from 'recoil';
// Example of handling different states
const handleLoadable = (loadable) => {
if (loadable.state === 'hasValue') {
console.log('Data:', loadable.getValue());
} else if (loadable.state === 'loading') {
console.log('Loading...');
} else if (loadable.state === 'hasError') {
console.error('Error:', loadable.errorOrThrow());
}
};