Form schema

Return

Learn how the Return element is used in the schema.


Usage

The Return element is used to define what the multi-step form returns. This element will trigger the onReturn callback function of the Formity component.

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

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

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

import { Step, Layout, TextField, NextButton } from "./components";

import { MultiStep } from "./multi-step";

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

export const schema: Schema<Values> = [
  {
    form: {
      values: () => ({
        name: ["", []],
        surname: ["", []],
      }),
      render: ({ values, onNext, onBack, getState, setState }) => (
        <MultiStep
          step="nameSurname"
          onNext={onNext}
          onBack={onBack}
          getState={getState}
          setState={setState}
        >
          <Step
            defaultValues={values}
            resolver={zodResolver(
              z.object({
                name: z.string(),
                surname: z.string(),
              }),
            )}
          >
            <Layout
              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={<NextButton>Next</NextButton>}
            />
          </Step>
        </MultiStep>
      ),
    },
  },
  {
    return: ({ name, surname }) => ({
      fullName: `${name} ${surname}`,
    }),
  },
];

We need to use the Return type and define the types of the values to be returned:

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

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

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

The return function takes the values generated in previous steps and returns the values to be returned.