@d3vtool/hooks
Version:
Collection of custom React hooks to simplify tasks in your React projects.
47 lines (46 loc) • 2.13 kB
TypeScript
import { Dispatch, SetStateAction } from "react";
import { InitializerAction } from "../Hub/Hub";
import { PromiseAction } from "./usePromiseHub";
export type PromiseHubError<E> = E | null;
export type PromiseHubType<R, E> = {
currentState: R;
pending: boolean;
error: PromiseHubError<E>;
};
export type PromiseListener<R, E> = Dispatch<SetStateAction<PromiseHubType<R, E>>>;
export declare class PromiseHub<R, E = Error> {
private promiseState;
private promiseAction;
private onChangeListeners;
private listeners;
constructor(initialState: R, promiseAction: PromiseAction<R>);
reAction(): Promise<R | undefined>;
attachListener(listener: PromiseListener<R, E>): void;
detachListener(listener: PromiseListener<R, E>): void;
notifyListeners(newPromiseState: PromiseHubType<R, E>): void;
getCurrentState(): R;
setCurrentState(newCurrentState: R): void;
setPendingState(pendingState: boolean): void;
getPendingState(): boolean;
getErrorState(): PromiseHubError<E>;
setErrorState(error: E): void;
onChange(callback: Function): void;
removeOnChange(callback: Function): void;
}
/**
* Creates a promise-based hub that manages a state and handles asynchronous actions.
* The state is updated based on the result of the provided promise action, allowing
* for easy state management involving async operations such as API calls.
*
* @template R - The type of the state managed by the promise hub.
*
* @param {R | InitializerAction<R>} initialState - The initial state or a function to initialize the state.
* @param {PromiseAction<R>} promiseAction - The asynchronous function that will resolve to update the state.
*
* @returns {PromiseHub<R>} - Returns a PromiseHub which contains the current state, a loading flag, an error state, and a method to trigger the promise action.
*
* @example
* // Example usage of `createPromiseHub`:
* const userHub = createPromiseHub<User | undefined>(undefined, fetchUserData);
*/
export declare function createPromiseHub<R>(initialState: R | InitializerAction<R>, promiseAction: PromiseAction<R>): PromiseHub<R>;