mirror of
https://github.com/muerwre/vault-frontend.git
synced 2025-04-25 04:46:40 +07:00
refactored hooks directory
This commit is contained in:
parent
efa3ba902d
commit
f76a5a4798
106 changed files with 122 additions and 144 deletions
69
src/hooks/node/useNodeFormFormik.ts
Normal file
69
src/hooks/node/useNodeFormFormik.ts
Normal file
|
@ -0,0 +1,69 @@
|
|||
import { INode } from '~/redux/types';
|
||||
import { FileUploader } from '~/hooks/data/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>();
|
Loading…
Add table
Add a link
Reference in a new issue