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.**
82 lines • 2.37 kB
TypeScript
import { Option } from "ts-results-es";
export type ValyncOptions<T> = {
init?: Omit<RequestInit, "signal">;
cache?: boolean;
fetchOnMount?: boolean;
retryCount?: number;
onData?: (data: any) => T;
watch?: any[];
initialData?: ApiResponse<T>;
fetchInterval?: number;
onSuccess?: (data: T) => void;
onError?: (err: ApiErrorResponse["error"]) => void;
};
export type CacheKey = string | ({
url: string;
} & Record<string, any>);
export declare function normalizeKey(key: CacheKey): string;
export type ApiErrorResponse = {
status: "failed";
error: {
name: string;
message: string;
code?: number | string;
};
};
export type ApiSuccessResponse<T> = {
status: "success";
data: T;
};
export type ApiResponse<T> = ApiSuccessResponse<T> | ApiErrorResponse;
export type Handler<T, R> = {
loading?: () => R;
error?: (err: {
name: string;
message: string;
code?: number | string;
}) => R;
data?: (value: Option<T>) => R;
};
export type RequestMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
export type StateListener<T> = (val: AsyncValue<T>) => void;
export interface Observer<T> {
listen: (fn: StateListener<T>) => () => void;
}
export declare class AsyncObserver<T> {
private _current;
constructor(_current: AsyncValue<T>);
private listeners;
listen(fn: StateListener<T>): () => boolean;
observer(): {
listen: (fn: StateListener<T>) => () => boolean;
};
set(val: AsyncValue<T>): void;
}
export declare abstract class AsyncValue<T> {
abstract when<R>(handlers: Handler<T, R>): R;
isLoading(): this is AsyncLoading;
isData(): this is AsyncData<T>;
isError(): this is AsyncError;
}
export declare class AsyncLoading<T = unknown> extends AsyncValue<T> {
when<R>(h: Handler<T, R>): R;
}
export declare class AsyncError<T = unknown> extends AsyncValue<T> {
error: {
name: string;
message: string;
code?: string | number;
};
constructor(error: {
name: string;
message: string;
code?: string | number;
});
when<R>(h: Handler<T, R>): R;
}
export declare class AsyncData<T> extends AsyncValue<T> {
value: Option<T>;
constructor(value: Option<T>);
when<R>(h: Handler<T, R>): R;
}
//# sourceMappingURL=index.d.ts.map