• The fallback middleware adds fallback value when an error occurs.

    IMPORT_PATH: "@daiso-tech/core/async"

    Type Parameters

    • TParameters extends unknown[]
    • TReturn
    • TContext extends Partial<Record<string | symbol, unknown>>

    Parameters

    Returns AsyncMiddlewareFn<TParameters, TReturn, TContext>

    import { fallback } from "@daiso-tech/core/async";
    import { AsyncHooks } from "@daiso-tech/core/utilities";

    const fetchData = new AsyncHooks(async (url: string): Promise<unknown> => {
    const response = await fetch(url);
    const json = await response.json();
    if (!response.ok) {
    throw json
    }
    return json;
    }, [
    fallback({ fallbackValue: null })
    ]);

    // Will return null when the fetch method throws an error.
    console.log(await fetchData.invoke("URL_ENDPOINT"));

    The middleware works also when the function returns a Result type.

    import { fallback } from "@daiso-tech/core/async";
    import { AsyncHooks, Result, resultFailure, resultSuccess } from "@daiso-tech/core/utilities";

    const fetchData = new AsyncHooks(async (url: string): Promise<Result> => {
    const response = await fetch(url);
    const json = await response.json();
    if (!response.ok) {
    return resultFailure(json);
    }
    return resultSuccess(json);
    }, [
    fallback({ fallbackValue: null })
    ]);

    // Will return null when the fetch method throws an error.
    console.log(await fetchData.invoke("URL_ENDPOINT"));