mirror of
https://github.com/muerwre/vault-frontend.git
synced 2025-04-25 12:56:41 +07:00
#34 added isLoading and error handling to useCommentFormFormik
This commit is contained in:
parent
8ae2dc02f0
commit
d7b4fbf535
2 changed files with 50 additions and 13 deletions
|
@ -1,7 +1,7 @@
|
|||
import { IFile } from '~/redux/types';
|
||||
import { useRef, useState } from 'react';
|
||||
import { useFormik, useFormikContext } from 'formik';
|
||||
import { object, string, array } from 'yup';
|
||||
import { IComment, IFile } from '~/redux/types';
|
||||
import { useCallback, useRef } from 'react';
|
||||
import { FormikHelpers, useFormik, useFormikContext } from 'formik';
|
||||
import { array, object, string } from 'yup';
|
||||
|
||||
export interface CommentFormValues {
|
||||
text: string;
|
||||
|
@ -15,21 +15,50 @@ const validationSchema = object().shape({
|
|||
songs: array(),
|
||||
});
|
||||
|
||||
export const useCommentFormFormik = (
|
||||
const submitComment = async (
|
||||
id: IComment['id'],
|
||||
values: CommentFormValues,
|
||||
onSubmit: (values: CommentFormValues) => void
|
||||
callback: (e: string) => void
|
||||
) => {
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
callback('wrong');
|
||||
};
|
||||
|
||||
export const useCommentFormFormik = (values: CommentFormValues) => {
|
||||
const { current: initialValues } = useRef(values);
|
||||
|
||||
const onSuccess = useCallback(
|
||||
({ resetForm, setStatus, setSubmitting }: FormikHelpers<CommentFormValues>) => (e: string) => {
|
||||
setSubmitting(false);
|
||||
|
||||
if (e) {
|
||||
setStatus(e);
|
||||
return;
|
||||
}
|
||||
|
||||
if (resetForm) {
|
||||
resetForm();
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const onSubmit = useCallback(
|
||||
(values: CommentFormValues, helpers: FormikHelpers<CommentFormValues>) => {
|
||||
helpers.setSubmitting(true);
|
||||
submitComment(0, values, onSuccess(helpers));
|
||||
},
|
||||
[values, onSuccess]
|
||||
);
|
||||
|
||||
const formik = useFormik({
|
||||
initialValues,
|
||||
validationSchema,
|
||||
onSubmit,
|
||||
initialStatus: '',
|
||||
});
|
||||
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
return { formik, isLoading };
|
||||
return { formik };
|
||||
};
|
||||
|
||||
export const useCommentFormContext = () => useFormikContext<CommentFormValues>();
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue