How do I get a correctly typed value after submitting a form? #445
Replies: 1 comment 1 reply
-
|
I do not have the correct answer but these are my two cents : You can access the field value directly, if the form is in success mode, which comes after a succesful validation : const email = form.status === "success" ? fields.email.value : null;But this will not work if you have a client-side validation (it will trigger client-side and not wait for the server to process the email). Another approach can be to return explicit values from the action : export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const submission = parseWithZod(formData, { schema });
if (submission.status !== 'success') {
return json({ result: submission.reply(), returnedEmail: null});
}
// A real example would have a function like `issuePasswordReset` that would
// send an email to the user with a link to reset their password.
return json({
result: submission.reply(),
returnedEmail: submission.value.email,
});
}
export default function PasswordReset() {
const actionData = useActionData<typeof action>();
const [form, fields] = useForm({
lastResult: actionData?.result,
onValidate({ formData }) {
return parseWithZod(formData, { schema });
},
});
const email = actionData?.returnedEmail;
if (email) {
return <div>An email has been sent to {email}</div>;
}
return (
<Form method="post" {...getFormProps(form)}>
<div>
<label>Email</label>
<input {...getInputProps(fields.email, { type: 'email' })} />
</div>
<hr />
<button>Reset My Password</button>
</Form>
);
}This works well but it is not very clean as you have to explicitly specify returnedEmail in your json response to make Typescript happy again. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I have a few cases in my Remix application where a form is submitted and the user remains on the same route. In some cases I am using one or more of the submitted values in the template.
I'm accessing the value(s) with
useActionData()and theinitialValueproperty, but the typing is incorrect.I put together a relatively simple example of this with a password reset form where the user submits their email and we display the email address on the page after the form has been submitted. https://stackblitz.com/edit/conform-type-test?file=app%2Froutes%2Fpassword-reset.tsx
The problem is that TypeScript thinks the email is an empty object,
{}, instead of a string."Type '{}' is not assignable to type 'ReactNode'."I can hack around it by changing:
to:
but it feels like I'm missing something or misunderstanding something.
Is there a better way to access the correctly typed values after submitting a form?
Beta Was this translation helpful? Give feedback.
All reactions