Remix Validated Form

(formId: string, defaultValues: any) => FormDefaults

Automatically set the default values of a form from your loader.

Basic Usage

To use this, the ValidatedForm must have an id.

import { json, LoaderFunction } from "remix";
import { setFormDefaults } from "remix-validated-form";

export const loader: LoaderFunction = () => {
  return json(
    setFormDefaults("myForm", {
      firstName: "John",
      lastName: "Doe",
    })
  );
};

export default function MyForm() {
  return (
    <ValidatedForm id="myForm">
      Required props and form elements omitted for brevity
    </ValidatedForm>
  );
}

Note: This does not return a response like validationError does. Instead, it returns data that's meant to be included in remix's own json response.

Usage with other loader data

Often, you'll want to include other data in your loader's response. You can do that like this:

import { json, LoaderFunction } from "remix";
import {
  setFormDefaults,
  FormDefaults,
} from "remix-validated-form";

type LoaderData = { message: string };

export const loader: LoaderFunction = () => {
  return json<LoaderData & FormDefaults>({
    message: "Hello World!",
    ...setFormDefaults("myForm", {
      firstName: "John",
      lastName: "Doe",
    }),
  });
};

Setting multiple forms at once

You can also set the default values for multiple forms at once

import { json, LoaderFunction } from "remix";
import {
  setFormDefaults,
  FormDefaults,
} from "remix-validated-form";

export const loader: LoaderFunction = () => {
  return json<FormDefaults>({
    ...setFormDefaults("myForm", {
      firstName: "John",
      lastName: "Doe",
    }),
    ...setFormDefaults("myOtherForm", {
      favoriteFood: "Pizza",
    }),
  });
};

Order of precedence

It's possible to have default values set in multiple places.