Form schema

Variables

Learn how the Variables element is used in the schema.


Usage

The Variables element is used to define variables.

To understand how it is used let's look at this example:

import type { Schema, Form, Return, Variables } from "@formity/react";

import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

import { FormView, FormLayout, TextField, Next } from "./components";

import { Controller } from "./controller";

export type Values = [
  Form<{ name: string; surname: string }>,
  Variables<{ fullName: string }>,
  Return<{ fullName: string }>,
];

export const schema: Schema<Values> = [
  {
    form: {
      values: () => ({
        name: ["", []],
        surname: ["", []],
      }),
      render: ({ values, onNext, onBack, getState, setState }) => (
        <Controller
          step="name-surname"
          onNext={onNext}
          onBack={onBack}
          getState={getState}
          setState={setState}
        >
          <FormView
            defaultValues={values}
            resolver={zodResolver(
              z.object({
                name: z.string(),
                surname: z.string(),
              }),
            )}
          >
            <FormLayout
              heading="What is your name?"
              description="We would like to know what is your name"
              fields={[
                <TextField key="name" name="name" label="Name" />,
                <TextField key="surname" name="surname" label="Surname" />,
              ]}
              button={<Next>Next</Next>}
            />
          </FormView>
        </Controller>
      ),
    },
  },
  {
    variables: ({ name, surname }) => ({
      fullName: `${name} ${surname}`,
    }),
  },
  {
    return: ({ fullName }) => ({
      fullName,
    }),
  },
];

We need to use the Variables type and define the types of the variables:

export type Values = [
  // ...
  Variables<{ fullName: string }>,
  // ...
];

Then, in the schema we need to create an object with the following structure:

export const schema: Schema<Values> = [
  // ...
  {
    variables: ({ name, surname }) => ({
      fullName: `${name} ${surname}`,
    }),
  },
  // ...
];

The variables function takes the values generated in previous steps and returns the variables to be created.