valync
Version:
**A lightweight, framework-agnostic async data handling library for React & Vue, inspired by Riverpod’s AsyncValue pattern and powered by ts-results-es.**
70 lines • 1.76 kB
JavaScript
// Normalize cache key (convert object to stable string)
export function normalizeKey(key) {
if (typeof key === "string")
return key;
const { url, ...params } = key;
const search = new URLSearchParams(params);
return `${url}?${search.toString()}`;
}
export class AsyncObserver {
constructor(_current) {
this._current = _current;
this.listeners = new Set();
}
listen(fn) {
fn(this._current);
this.listeners.add(fn);
return () => this.listeners.delete(fn);
}
observer() {
return {
listen: (fn) => {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
},
};
}
set(val) {
this._current = val;
this.listeners.forEach((fn) => fn(val));
}
}
// Base abstract class for async state
export class AsyncValue {
isLoading() {
return this instanceof AsyncLoading;
}
isData() {
return this instanceof AsyncData;
}
isError() {
return this instanceof AsyncError;
}
}
// Represents loading state
export class AsyncLoading extends AsyncValue {
when(h) {
return h.loading ? h.loading() : undefined;
}
}
// Represents failed state with error
export class AsyncError extends AsyncValue {
constructor(error) {
super();
this.error = error;
}
when(h) {
return h.error ? h.error(this.error) : undefined;
}
}
// Represents data state—with Some(T) or None
export class AsyncData extends AsyncValue {
constructor(value) {
super();
this.value = value;
}
when(h) {
return h.data ? h.data(this.value) : undefined;
}
}
//# sourceMappingURL=index.js.map