Skip to content

Commit

Permalink
fix: split lines
Browse files Browse the repository at this point in the history
  • Loading branch information
SKairinos committed Oct 10, 2024
1 parent b197fd8 commit 59a8ee6
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions src/components/form/TextField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ import {
} from "@mui/material"
import { Field, type FieldConfig, type FieldProps } from "formik"
import { type FC, useState, useEffect } from "react"
import { type StringSchema, type ValidateOptions } from "yup"
import {
type StringSchema,
type ValidateOptions,
array as YupArray,
type Schema,
} from "yup"

import { schemaToFieldValidator } from "../../utils/form"
import { getNestedProperty } from "../../utils/general"
Expand All @@ -23,6 +28,7 @@ export type TextFieldProps = Omit<
schema: StringSchema
validateOptions?: ValidateOptions
dirty?: boolean
split?: string | RegExp
}

// https://formik.org/docs/examples/with-material-ui
Expand All @@ -33,20 +39,24 @@ const TextField: FC<TextFieldProps> = ({
type = "text",
required = false,
dirty = false,
split,
validateOptions,
...otherTextFieldProps
}) => {
const [initialValue, setInitialValue] = useState("")
const [initialValue, setInitialValue] = useState<string | string[]>("")

const dotPath = name.split(".")

if (required) schema = schema.required()
if (dirty) schema = schema.notOneOf([initialValue], "cannot be initial value")
let _schema: Schema = schema
if (split) _schema = YupArray().of(_schema)
if (required) _schema = _schema.required()
if (dirty)
_schema = _schema.notOneOf([initialValue], "cannot be initial value")

const fieldConfig: FieldConfig = {
name,
type,
validate: schemaToFieldValidator(schema, validateOptions),
validate: schemaToFieldValidator(_schema, validateOptions),
}

const _Field: FC<FieldProps> = ({ form }) => {
Expand All @@ -59,6 +69,10 @@ const TextField: FC<TextFieldProps> = ({
setInitialValue(initialValue)
}, [initialValue])

useEffect(() => {
form.setFieldValue(name, split ? value.split(split) : value, true)
}, [value]) // eslint-disable-line react-hooks/exhaustive-deps

return (
<MuiTextField
id={id ?? name}
Expand Down

0 comments on commit 59a8ee6

Please sign in to comment.