Search code examples
typescriptremix.runzod

implementing multiple forms in remix with ZOD


How can I use zod to handle multiple forms in remix?:
say I want to get some input value named "_intent" and parse the right form data based on the value.

The problem I'm facing is that I get errors because not all forms sends the same formData...


Solution

  • I ended up doing this:

    export const action = async ({ request }: ActionArgs) => {
      const formData = await request.formData();
      const allFormDataFields = Object.fromEntries(formData.entries());
    
      // first extract the intent
      const intent = allFormDataFields._intent as keyof typeof FormIntents;
    
      if (intent === FormIntents.add_transaction) {
        // now parse with relevant zod object
        const result =
          myZodObject.safeParse(allFormDataFields);
        if (!result.success) {
          return badRequest({
            errorFields: result.error.flatten(),
          });
        }
        // do stuff
      } 
      if(intent === "something else"){
        // do other stuff
      }