useSubmit
This hook is based on useLoad
. It reduces many functions for convenience, and it only supports a few options. Specially, it will never execute automatically. This hook is usually used for network requests such as creating, updating and deleting, but not reading. The LoadConfig
component can only set some of the options listed below for this hook.
API
type PromiseResolve<T extends Promise<any>> = T extends Promise<infer P>
? P
: never;
type LoadCallback = (...args: any[]) => Promise<any>;
type LoadData<T extends LoadCallback> = PromiseResolve<ReturnType<T>>;
function useSubmit<Callback extends LoadCallback>(
callback: Callback,
options?: {
idle?: boolean;
fallback?: Callback;
retry?: boolean;
retryLimit?: number;
retryInterval?: number | ((count: number) => number);
fallbackRetry?: boolean;
fallbackRetryLimit?: number;
fallbackRetryInterval?: number | ((count: number) => number);
onSuccess?: (data: LoadData<Callback>) => void;
onFailure?: (error: any) => void;
onFinally?: () => void;
}
): {
submitting: boolean;
submit: (...params: Parameters<Callback>) => ReturnType<Callback>;
};
Params:
callback
: A function returns a promise object.options
: Options object.options.idle
: Run callback during the browser's idle periods. You can set an object contains atimeout
property to limit the max waiting time.options.fallback
: When thecallback
function reject an error and the count of retries has been exhausted, thefallback
function will be called.options.retry
: Enable retry callback. Default isfalse
.options.retryLimit
: Callback retry limit. Default is3
.options.retryInterval
: Callback retry interval. Default is0
. You can set a function that returns a number value for this option, for example(count) => Math.pow(2, count)
.options.fallbackRetry
: Enable retry fallback. Default isfalse
.options.fallbackRetryLimit
: Fallback retry limit. Default is3
.options.fallbackRetryInterval
: Fallback retry interval. It also can be a function.options.onSuccess
: Success event.options.onFailure
: Failure event.options.onFinally
: Finally event.
Results:
submitting
: Submitting state. Initial value isfalse
.submit
: Submit function. Used in the same way as thecallback
.
Example
Number: (Loading...)
import React from "react";
import { useLoad, useSubmit } from "@lilib/hooks";
const getNumber = () => {
return new Promise<number>((resolve) => {
setTimeout(() => {
resolve(Math.random());
}, 1000);
});
};
function Example() {
const { data, loading, update, reload } = useLoad(getNumber);
const { submit, submitting } = useSubmit(getNumber, {
onSuccess: (result) => {
update(result);
reload();
},
});
return (
<div>
<button onClick={() => submit()}>
{submitting ? "Submitting" : "Submit"}
</button>
Number: {data} {loading ? "(Loading...)" : ""}
</div>
);
}
export default Example;