Field value (return of useForm) disappear when input value change #668
-
When I change email input value, id and name of two student disappeared. 'use client';
import { getFormProps, getInputProps, useForm } from '@conform-to/react';
import { parseWithZod } from '@conform-to/zod';
import { z } from 'zod';
export default function Page() {
const schema = z.object({
students: z
.object({
id: z.number(),
name: z.string(),
email: z.string(),
})
.array(),
});
type schemaType = z.infer<typeof schema>;
const testObj: schemaType = {
students: [
{
id: 1,
name: 'a',
email: 'a@a.a',
},
{
id: 2,
name: 'b',
email: 'b@b.b',
},
],
};
const [form, fields] = useForm({
defaultValue: testObj,
onValidate({ formData }) {
return parseWithZod(formData, { schema: schema });
},
shouldValidate: 'onBlur',
});
const students = fields.students.getFieldList();
return (
<>
<form {...getFormProps(form)}>
{students.map((student) => {
const studentField = student.getFieldset();
const { key: studendKey, ...emailFieldProps } = getInputProps(studentField.email, {
type: 'text',
});
return (
<div key={student.id}>
id:{studentField.id.value}
<br />
name:{studentField.name.value}
<br />
email:<input {...emailFieldProps}></input>
<br />
</div>
);
})}
</form>
</>
);
} |
Beta Was this translation helpful? Give feedback.
Answered by
edmundhung
Jun 5, 2024
Replies: 1 comment 2 replies
-
Conform does not maintain any of the value and always uses the DOM (FormData) as the source of truth. If you wanna persist the data, you will need to render a hidden input for both id and name as well, like this: export function Example() {
// ...
return (
<>
<form {...getFormProps(form)}>
{students.map((student) => {
const studentField = student.getFieldset();
const { key: studendKey, ...emailFieldProps } = getInputProps(studentField.email, {
type: 'text',
});
return (
<div key={student.id}>
<input {...getInputProps(studentField.id, { type: 'hidden' })} />
id:{studentField.id.value}
<br />
<input {...getInputProps(studentField.name, { type: 'hidden' })} />
name:{studentField.name.value}
<br />
email:<input {...emailFieldProps}></input>
<br />
</div>
);
})}
</form>
</>
);
} |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
WMinsane
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Conform does not maintain any of the value and always uses the DOM (FormData) as the source of truth. If you wanna persist the data, you will need to render a hidden input for both id and name as well, like this: