1
0
Fork 0
mirror of https://github.com/muerwre/vault-frontend.git synced 2025-04-25 04:46:40 +07:00
vault-frontend/src/utils/hooks/node/useNodeFormFormik.ts
muerwre c2d1c2bfc9
99 use swr (#100)
* 99: made node use SWR

* 99: fixed comments for SWR node

* 99: added error toast to useNodeFormFormik.ts
2022-01-02 17:10:21 +07:00

69 lines
1.7 KiB
TypeScript

import { INode } from '~/redux/types';
import { FileUploader } from '~/utils/hooks/useFileUploader';
import { useCallback, useRef } from 'react';
import { FormikConfig, FormikHelpers, useFormik, useFormikContext } from 'formik';
import { object } from 'yup';
import { keys } from 'ramda';
import { showErrorToast } from '~/utils/errors/showToast';
const validationSchema = object().shape({});
const afterSubmit = ({ resetForm, setStatus, setSubmitting, setErrors }: FormikHelpers<INode>) => (
e?: string,
errors?: Record<string, string>
) => {
setSubmitting(false);
if (e) {
setStatus(e);
showErrorToast(e);
return;
}
if (errors && keys(errors).length) {
setErrors(errors);
return;
}
if (resetForm) {
resetForm();
}
};
export const useNodeFormFormik = (
values: INode,
uploader: FileUploader,
stopEditing: () => void,
sendSaveRequest: (node: INode) => Promise<unknown>
) => {
const { current: initialValues } = useRef(values);
const onReset = useCallback(() => {
uploader.setFiles([]);
if (stopEditing) stopEditing();
}, [uploader, stopEditing]);
const onSubmit = useCallback<FormikConfig<INode>['onSubmit']>(
async (values, helpers) => {
try {
await sendSaveRequest({ ...values, files: uploader.files });
afterSubmit(helpers)();
} catch (error) {
afterSubmit(helpers)(error?.response?.data?.error, error?.response?.data?.errors);
}
},
[sendSaveRequest, uploader.files]
);
return useFormik<INode>({
initialValues,
validationSchema,
onSubmit,
onReset,
initialStatus: '',
validateOnChange: true,
});
};
export const useNodeFormContext = () => useFormikContext<INode>();