@sv-use/core
Version:
A collection of Svelte 5 utilities.
61 lines (60 loc) • 1.7 kB
JavaScript
/**
* A reactive state that handles the loading and error states of a promise.
* @param promise The promise to handle.
* @param initial The initial value of the state.
* @param options Additional options to customize the behavior.
* @see https://svelte-librarian.github.io/sv-use/docs/core/async-state
*/
export function asyncState(promise, initial, options = {}) {
const { immediate = true, resetOnExecute = false, onSuccess = () => { }, onError = () => { } } = options;
let _isLoading = $state(false);
let _isReady = $state(false);
let _error = $state(null);
let _current = $state(initial);
async function execute(...args) {
if (resetOnExecute) {
_current = initial;
}
_isReady = false;
_isLoading = true;
const _promise = typeof promise === 'function' ? promise(...args) : promise;
try {
const result = await _promise;
_current = result;
_isReady = true;
onSuccess(result);
}
catch (error) {
_error = error;
onError(error);
}
finally {
_isLoading = false;
}
}
if (immediate) {
// @ts-expect-error Types are not resolved properly
execute();
}
return {
get current() {
return _current;
},
set current(v) {
_current = v;
},
get isReady() {
return _isReady;
},
get isLoading() {
return _isLoading;
},
get error() {
return _error;
},
set error(v) {
_error = v;
},
execute
};
}