Skip to main content
Version: 2.x.x

useSubmit


Introduction

This hook mutates data on the server and supports controlling requests. It uses the Submit Dispatcher to handle requests and the Cache to manage the overall state of the data.

The minimum requirement for useSubmit is a prepared Command.

If you intend to retrieve data from the server, we recommend choosing the useFetch hook.


Initialization

const { submit, submitting, onSubmitSuccess, onSubmitError, onSubmitFinished } = useSubmit(postLogin);

How it works?

useSubmit executes a command when a submit() function returned from it gets triggered. It uses dependency tracking to limit re-rendering and improve performance. Under the hood, communication with the core systems is established by event emitters. Many "helper hooks" (such as onSubmitSuccess, onSubmitError, onSubmitFinished, etc.) are returned; these will help handle the request flow and lifecycle. This approach avoids overloading the base hook with callback logic. It also helps improve code readability, decreases code complication, and promotes more organized code.

import { useSubmit } from "@hyper-fetch/react";
import { postLogin } from "server";

interface Values {
email: string;
password: string;
}

const LoginPage: React.FC = () => {
const { submit, submitting, onSubmitSuccess, onSubmitError, onSubmitFinished } = useSubmit(postLogin);

onSubmitSuccess(({ response }) => {
console.log(response); // { token: string, refreshToken: string }
});

onSubmitError(({ response }) => {
console.log(response); // { message: string }
});

onSubmitFinished(({ response }) => {
const [payload, error, status] = response;
console.log(payload); // { token: string, refreshToken: string } | null
console.log(error); // { message: string } | null
console.log(status); // 200 / 400 / 404 / 500 ...
});

const onSubmit = (values: Values) => {
submit({ data: values });
};

return (
<Formik initialValues={initialValues} onSubmit={onSubmit} validationSchema={validationSchema}>
<Form>
{error && <Alert severity="error">{error.error_message}</Alert>}
<FormInput name="email" label="Email" placeholder="Fill your email" />
<FormInput type="password" name="password" label="Password" placeholder="Fill your password" />
<Button type="submit" variant="contained" disabled={submitting} className={styles.submit}>
Log in
</Button>
</Form>
</Formik>
);
};

Passing data and params

Data and parameters can be passed in several ways. One option is to use methods on the Command, such as setData or setParams.

const { submit } = useSubmit(patchUser.setParams({ userId: 1 }).setData({ name: "New Name" }));

However, you may need to pass parameters dynamically, which requires using submit function options.

const { submit } = useSubmit(patchUser);

const handleSubmit = (id: number, name: string) => {
submit({ data: { name }, params: { userId: id }, queryParams: { search: "test" } });
};

Options

These configuration options should be provided as a second parameter:

const { ... } = useSubmit(command, options)

{
bounce: boolean;
bounceTime: number;
bounceType: debounce | throttle;
deepCompare: boolean | typeof isEqual;
dependencyTracking: boolean;
disabled: boolean;
initialData: ClientResponseType<Response, Error> | null;
}


Returns

Returned values from this hook:

const values = useSubmit(command);

{
data: null | T extends Command<infer D, any, any, any, any, any, any, any, any, any, any> ? D : never;
error: null | T extends Command<any, any, any, infer G, infer L, any, any, any, any, any, any> ? G | L : never;
retries: number;
status: null | number;
timestamp: null | Date;
setData: (data: ExtractResponse<T>, emitToCache?: boolean) => void;
setError: (error: ExtractError<T>, emitToCache?: boolean) => void;
setLoading: (loading: boolean, emitToHooks?: boolean) => void;
setRetries: (retries: number, emitToCache?: boolean) => void;
setStatus: (status: number | null, emitToCache?: boolean) => void;
setTimestamp: (timestamp: Date, emitToCache?: boolean) => void;
abort: () => void;
bounce: {
active: boolean;
reset: () => void;
};
onSubmitAbort: (callback: OnErrorCallbackType<CommandType>) => void;
onSubmitDownloadProgress: (callback: OnProgressCallbackType) => void;
onSubmitError: (callback: OnErrorCallbackType<CommandType>) => void;
onSubmitFinished: (callback: OnFinishedCallbackType<CommandType>) => void;
onSubmitOfflineError: (callback: OnErrorCallbackType<CommandType>) => void;
onSubmitRequestStart: (callback: OnStartCallbackType<CommandType>) => void;
onSubmitResponseStart: (callback: OnStartCallbackType<CommandType>) => void;
onSubmitSuccess: (callback: OnSuccessCallbackType<CommandType>) => void;
onSubmitUploadProgress: (callback: OnProgressCallbackType) => void;
revalidate: (invalidateKey: InvalidationKeyType | InvalidationKeyType[]) => void;
submit: FetchType<Command>[data] extends NegativeTypes ? (FetchType<Command>[params] extends NegativeTypes ? (options?: FetchType<Command>) => Promise<ClientResponseType<ExtractResponse<Command>, ExtractError<Command>>> : (options: FetchType<Command>) => Promise<ClientResponseType<ExtractResponse<Command>, ExtractError<Command>>>) : (options: FetchType<Command>) => Promise<ClientResponseType<ExtractResponse<Command>, ExtractError<Command>>>;
submitting: boolean;
}