Alerting: Update useAsync to typeguard states (#98884)

This commit is contained in:
Gilles De Mey 2025-01-13 15:20:48 +01:00 committed by GitHub
parent 9ec10be1c7
commit 4aa29c79a4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -8,23 +8,31 @@ import { stringifyErrorLike } from '../utils/misc';
export type AsyncStatus = 'loading' | 'success' | 'error' | 'not-executed'; export type AsyncStatus = 'loading' | 'success' | 'error' | 'not-executed';
export type AsyncState<Result> = export type AsyncState<Result> =
| { | AsyncStateUninitialized<Result>
status: 'not-executed'; | AsyncStateFulfilled<Result>
error: undefined; | AsyncStateWithError<Result>
result: Result; | AsyncStateLoading<Result>;
}
| { export type AsyncStateWithError<Result> = {
status: 'success';
error: undefined;
result: Result;
}
| {
status: 'error'; status: 'error';
error: Error; error: Error;
result: Result; result: Result;
} };
| {
status: AsyncStatus; export type AsyncStateFulfilled<Result> = {
status: 'success';
error: undefined;
result: Result;
};
export type AsyncStateUninitialized<Result> = {
status: 'not-executed';
error: undefined;
result: Result;
};
export type AsyncStateLoading<Result> = {
status: 'loading';
error: Error | undefined; error: Error | undefined;
result: Result; result: Result;
}; };
@ -157,19 +165,19 @@ function useSyncedRef<T>(value: T): { readonly current: T } {
// --- utility functions to help with request state assertions --- // --- utility functions to help with request state assertions ---
export function isError<T>(state: AsyncState<T>) { export function isError<T>(state: AsyncState<unknown>): state is AsyncStateWithError<T> {
return state.status === 'error'; return state.status === 'error';
} }
export function isSuccess<T>(state: AsyncState<T>) { export function isSuccess<T>(state: AsyncState<T>): state is AsyncStateFulfilled<T> {
return state.status === 'success'; return state.status === 'success';
} }
export function isUninitialized<T>(state: AsyncState<T>) { export function isUninitialized<T>(state: AsyncState<T>): state is AsyncStateUninitialized<T> {
return state.status === 'not-executed'; return state.status === 'not-executed';
} }
export function isLoading<T>(state: AsyncState<T>) { export function isLoading<T>(state: AsyncState<T>): state is AsyncStateLoading<T> {
return state.status === 'loading'; return state.status === 'loading';
} }
@ -185,7 +193,7 @@ export function anyOfRequestState(...states: Array<AsyncState<unknown>>) {
/** /**
* This is only used for testing and serializing the async state * This is only used for testing and serializing the async state
*/ */
export function SerializeState({ state }: { state: AsyncState<unknown> }) { export function SerializeState<T>({ state }: { state: AsyncState<T> }) {
return ( return (
<> <>
{isUninitialized(state) && 'uninitialized'} {isUninitialized(state) && 'uninitialized'}