From 88672ae391aec6b66f4fc61de5307b9aff47581a Mon Sep 17 00:00:00 2001 From: breeg554 Date: Tue, 15 Oct 2024 14:05:26 +0200 Subject: [PATCH] update url field based on changed default value --- .../app/components/form/fields/text.field.tsx | 45 ++++++++++++++++--- 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/apps/web-remix/app/components/form/fields/text.field.tsx b/apps/web-remix/app/components/form/fields/text.field.tsx index ec2bc477b..3f4184235 100644 --- a/apps/web-remix/app/components/form/fields/text.field.tsx +++ b/apps/web-remix/app/components/form/fields/text.field.tsx @@ -1,5 +1,6 @@ -import React, { forwardRef, useRef } from 'react'; +import React, { forwardRef, useEffect, useRef } from 'react'; import { RefreshCcw } from 'lucide-react'; +import { useControlField } from 'remix-validated-form'; import type { ValidationBehaviorOptions } from 'remix-validated-form/browser/internal/getInputProps'; import { useFieldContext } from '~/components/form/fields/field.context'; @@ -30,12 +31,13 @@ export const TextInputField = forwardRef< aria-errormessage={error ? `${name}-error` : undefined} aria-label={name} autoComplete={name} - {...props} {...getInputProps()} + {...props} /> ); }); TextInputField.displayName = 'TextInputField'; + export const PasswordInputField = forwardRef< HTMLInputElement, Partial @@ -47,17 +49,41 @@ PasswordInputField.displayName = 'PasswordInputField'; export function ResettableTextInputField({ label, + defaultValue, ...props }: Partial & { label: string }) { - const inputRef = useRef(null); + const inputRef = useRef(null); + const { name } = useFieldContext({ + validationBehavior: { + initial: 'onChange', + whenTouched: 'onChange', + whenSubmitted: 'onChange', + }, + }); + + const [value, setValue] = useControlField(name); + + useEffect(() => { + if (typeof defaultValue === 'string') { + updateAndValidate(defaultValue); + } + }, [defaultValue]); const onReset = () => { - if (inputRef.current) { - inputRef.current.value = (props.defaultValue ?? '') as string; + if (typeof defaultValue === 'string') { + updateAndValidate(defaultValue); } }; - const canReset = !!props.defaultValue && !props.readOnly && !props.disabled; + const updateAndValidate = (newValue: string) => { + setValue(newValue); + }; + + const onChange = (e: React.ChangeEvent) => { + setValue(e.target.value); + }; + + const canReset = !!defaultValue && !props.readOnly && !props.disabled; return ( <> @@ -68,7 +94,12 @@ export function ResettableTextInputField({ {canReset ? : null} - + ); }