Skip to content

Commit

Permalink
fix: support dirty fields
Browse files Browse the repository at this point in the history
  • Loading branch information
SKairinos committed Sep 18, 2024
1 parent 11b25c4 commit d74c8e9
Showing 1 changed file with 32 additions and 24 deletions.
56 changes: 32 additions & 24 deletions src/components/form/TextField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -23,6 +23,7 @@ export type TextFieldProps = Omit<
name: string
schema: StringSchema
validateOptions?: ValidateOptions
dirty?: boolean
}

// https://formik.org/docs/examples/with-material-ui
Expand All @@ -31,43 +32,50 @@ const TextField: FC<TextFieldProps> = ({
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,
type,
validate: schemaToFieldValidator(schema, validateOptions),
}

return (
<Field {...fieldConfig}>
{({ form }: FieldProps) => {
const value = getNestedProperty(form.values, dotPath)
const error = getNestedProperty(form.errors, dotPath)
const touched = getNestedProperty(form.touched, dotPath)
const _Field: FC<FieldProps> = ({ 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 (
<MuiTextField
id={name}
name={name}
type={type}
required={required}
value={value}
onChange={form.handleChange}
onBlur={form.handleBlur}
error={touched && Boolean(error)}
helperText={(touched && error) as false | string}
{...otherTextFieldProps}
/>
)
}

return (
<MuiTextField
id={name}
name={name}
type={type}
required={required}
value={value}
onChange={form.handleChange}
onBlur={form.handleBlur}
error={touched && Boolean(error)}
helperText={(touched && error) as false | string}
{...otherTextFieldProps}
/>
)
}}
</Field>
)
return <Field {...fieldConfig}>{_Field}</Field>
}

export default TextField

0 comments on commit d74c8e9

Please sign in to comment.