Flow elementsYield

Flow elements

Yield

Learn how the yield element passes values to the onYield callback.


Usage

The yield element yields values while the multi-step form is in progress. When the flow passes through it, the onYield callback is called with those values and the flow continues.

TSX
// src/app.tsx
import { useCallback } from "react";

import {
  Formity,
  type s,
  type Flow,
  type OnYield,
  type OnReturn,
} from "@formity/react";

import { SeatForm } from "./components/seat-form";
import { EmailForm } from "./components/email-form";

type Schema = {
  render: React.ReactNode;
  struct: [
    s.Form<{ seat: string }>,
    s.Yield<{
      next: [{ type: "hold"; seat: string }];
      back: [{ type: "release"; seat: string }];
    }>,
    s.Form<{ email: string }>,
    s.Return<{ seat: string; email: string }>,
  ];
  inputs: Record<never, never>;
  params: Record<never, never>;
};

const flow: Flow<Schema> = [
  {
    form: {
      fields: () => ({ seat: ["", []] }),
      render: ({ fields, next }) => <SeatForm fields={fields} next={next} />,
    },
  },
  {
    yield: {
      next: ({ seat }) => [{ type: "hold", seat }],
      back: ({ seat }) => [{ type: "release", seat }],
    },
  },
  {
    form: {
      fields: () => ({ email: ["", []] }),
      render: ({ fields, back, next }) => (
        <EmailForm fields={fields} back={back} next={next} />
      ),
    },
  },
  {
    return: ({ seat, email }) => ({ seat, email }),
  },
];

export default function App() {
  const onYield = useCallback<OnYield<Schema>>((output) => {
    // | {
    //     type: "hold";
    //     seat: string;
    //   }
    // | {
    //     type: "release";
    //     seat: string;
    //   }
    console.log(output);
  }, []);

  const onReturn = useCallback<OnReturn<Schema>>((output) => {
    // {
    //   seat: string;
    //   email: string;
    // }
    console.log(output);
  }, []);

  return <Formity<Schema> flow={flow} onYield={onYield} onReturn={onReturn} />;
}

The next function is called when the flow passes through the yield element going forward. It receives the flow values and returns an array, and onYield is called once for each of its elements.

The back function is called when the flow passes through the yield element going backward. It receives the flow values and returns an array, and onYield is called once for each of its elements.

In the Schema, each yield element has an s.Yield entry in struct. Its next and back types must match the arrays returned by the next and back functions.

The OnYield<Schema> type is the type of the onYield callback, and YieldOutput<Schema> is the type of the values it receives, which is the union of the values of all the yield elements.