You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm not sure if it was intended that way, but I can see it being annoying in a longer form. Is there a way to fix this? It would be perfect for me if only the incorrect field ( or none at all ) reverted to default.
'use server';import{sql}from'@vercel/postgres';import{revalidatePath}from'next/cache';import{redirect}from'next/navigation';import{z}from'zod';constFormSchema=z.object({id: z.string(),customerId: z.string({invalid_type_error: 'Please select a customer.',}),amount: z.coerce.number().gt(0,{message: 'Please enter an amount greater than $0.'}),status: z.enum(['pending','paid'],{message: 'Please select an invoice status.',}),date: z.string(),});constCreateInvoice=FormSchema.omit({id: true,date: true});constUpdateInvoice=FormSchema.omit({id: true,date: true});exporttypeState={errors?: {customerId?: string[];amount?: string[];status?: string[];};message?: string|null;};exportasyncfunctioncreateInvoice(prevState: State,formData: FormData){// Validate form fields using ZodconstvalidatedFields=CreateInvoice.safeParse({customerId: formData.get('customerId'),amount: formData.get('amount'),status: formData.get('status'),});console.log(validatedFields);// If form validation fails, return errors early. Otherwise, continue.if(!validatedFields.success){return{errors: validatedFields.error.flatten().fieldErrors,message: 'Missing Fields. Failed to Create Invoice.',};}// Prepare data for insertion into the databaseconst{ customerId, amount, status }=validatedFields.data;constamountInCents=amount*100;constdate=newDate().toISOString().split('T')[0];try{awaitsql` INSERT INTO invoices (customer_id, amount, status, date) VALUES (${customerId}, ${amountInCents}, ${status}, ${date}) `;}catch(error){// If a database error occurs, return a more specific error.return{message: 'Database Error: Failed to Create Invoice.',};}// Revalidate the cache for the invoices page and redirect the user.revalidatePath('/dashboard/invoices');redirect('/dashboard/invoices');}exportasyncfunctionupdateInvoice(id: string,prevState: State,formData: FormData,){// Validate form fields using ZodconstvalidatedFields=UpdateInvoice.safeParse({customerId: formData.get('customerId'),amount: formData.get('amount'),status: formData.get('status'),});console.log(validatedFields);// If form validation fails, return errors early. Otherwise, continue.if(!validatedFields.success){return{errors: validatedFields.error.flatten().fieldErrors,message: 'Missing Fields. Failed to Update Invoice.',};}// Prepare data for insertion into the databaseconst{ customerId, amount, status }=validatedFields.data;constamountInCents=amount*100;try{awaitsql` UPDATE invoices SET customer_id = ${customerId}, amount = ${amountInCents}, status = ${status} WHERE id = ${id} `;}catch(error){return{message: 'Database Error: Failed to Update Invoice.'};}revalidatePath('/dashboard/invoices');redirect('/dashboard/invoices');}exportasyncfunctiondeleteInvoice(id: string){try{awaitsql`DELETE FROM invoices WHERE id = ${id}`;revalidatePath('/dashboard/invoices');return{message: 'Deleted Invoice.'};}catch(error){return{message: 'Database Error: Failed to Delete Invoice.'};}}
The text was updated successfully, but these errors were encountered:
EdoanR
changed the title
All forms reset to default if any input is invalid in 'Chapter 7 - Improving Accessibility.'
All form reset to default if any field is invalid in 'Chapter 7 - Improving Accessibility.'
Aug 28, 2024
@EdoanR
hey, wanna try my solution and see if it works? By the way, the official documentaion is written in the way where failure on data validation on form submission will wipe out previously entered good data, it was written that way
@EdoanR hey, wanna try my solution and see if it works? By the way, the official documentaion is written in the way where failure on data validation on form submission will wipe out previously entered good data, it was written that way
I tried right now and it works! I had to change the State properties to work, only for the customerId for now, but seems easy to implement for the other fields too. I still wish there's a better way to do it, looks relatively simple, I will keep this issue opened for now.
I'm not sure if it was intended that way, but I can see it being annoying in a longer form. Is there a way to fix this? It would be perfect for me if only the incorrect field ( or none at all ) reverted to default.
brave_YW8FidArR7.mp4
Here's the form code ( create-form.tsx ):
The actions ( action.ts )
The text was updated successfully, but these errors were encountered: