From d74c8e97010e15032dce4ca63ec65b8e012e7e53 Mon Sep 17 00:00:00 2001 From: SKairinos Date: Wed, 18 Sep 2024 10:14:50 +0000 Subject: [PATCH] fix: support dirty fields --- src/components/form/TextField.tsx | 56 ++++++++++++++++++------------- 1 file changed, 32 insertions(+), 24 deletions(-) diff --git a/src/components/form/TextField.tsx b/src/components/form/TextField.tsx index ed6b46c..d1ccf08 100644 --- a/src/components/form/TextField.tsx +++ b/src/components/form/TextField.tsx @@ -3,7 +3,7 @@ import { type TextFieldProps as MuiTextFieldProps, } from "@mui/material" import { Field, type FieldConfig, type FieldProps } from "formik" -import type { FC } from "react" +import { type FC, useState, useEffect } from "react" import { type StringSchema, type ValidateOptions } from "yup" import { schemaToFieldValidator } from "../../utils/form" @@ -23,6 +23,7 @@ export type TextFieldProps = Omit< name: string schema: StringSchema validateOptions?: ValidateOptions + dirty?: boolean } // https://formik.org/docs/examples/with-material-ui @@ -31,12 +32,16 @@ const TextField: FC = ({ schema, type = "text", required = false, + dirty = false, validateOptions, ...otherTextFieldProps }) => { + const [initialValue, setInitialValue] = useState("") + const dotPath = name.split(".") if (required) schema = schema.required() + if (dirty) schema = schema.notOneOf([initialValue], "cannot be initial value") const fieldConfig: FieldConfig = { name, @@ -44,30 +49,33 @@ const TextField: FC = ({ validate: schemaToFieldValidator(schema, validateOptions), } - return ( - - {({ form }: FieldProps) => { - const value = getNestedProperty(form.values, dotPath) - const error = getNestedProperty(form.errors, dotPath) - const touched = getNestedProperty(form.touched, dotPath) + const _Field: FC = ({ form }) => { + const initialValue = getNestedProperty(form.initialValues, dotPath) + const value = getNestedProperty(form.values, dotPath) + const error = getNestedProperty(form.errors, dotPath) + const touched = getNestedProperty(form.touched, dotPath) + + useEffect(() => { + setInitialValue(initialValue) + }, [initialValue]) + + return ( + + ) + } - return ( - - ) - }} - - ) + return {_Field} } export default TextField