Flow elements
Switch
Learn how the switch element branches the flow into multiple cases.
Usage
The switch element branches the flow based on multiple cases.
TSX
// src/app.tsx
import { useCallback } from "react";
import { Formity, type s, type Flow, type OnReturn } from "@formity/react";
import { InterestedForm } from "./components/interested-form";
import { WhyYesForm } from "./components/why-yes-form";
import { WhyNotForm } from "./components/why-not-form";
import { WhyNotSureForm } from "./components/why-not-sure-form";
type Schema = {
render: React.ReactNode;
struct: [
s.Form<{ interested: string }>,
s.Switch<{
branches: [
[
s.Form<{ whyYes: string }>,
s.Return<{ interested: "yes"; whyYes: string }>,
],
[
s.Form<{ whyNot: string }>,
s.Return<{ interested: "no"; whyNot: string }>,
],
];
default: [
s.Form<{ whyNotSure: string }>,
s.Return<{ interested: "notSure"; whyNotSure: string }>,
];
}>,
];
inputs: Record<never, never>;
params: Record<never, never>;
};
const flow: Flow<Schema> = [
{
form: {
fields: () => ({ interested: ["yes", []] }),
render: ({ fields, next }) => (
<InterestedForm fields={fields} next={next} />
),
},
},
{
switch: {
branches: [
{
case: ({ interested }) => interested === "yes",
then: [
{
form: {
fields: () => ({ whyYes: ["", []] }),
render: ({ fields, back, next }) => (
<WhyYesForm fields={fields} back={back} next={next} />
),
},
},
{
return: ({ whyYes }) => ({ interested: "yes", whyYes }),
},
],
},
{
case: ({ interested }) => interested === "no",
then: [
{
form: {
fields: () => ({ whyNot: ["", []] }),
render: ({ fields, back, next }) => (
<WhyNotForm fields={fields} back={back} next={next} />
),
},
},
{
return: ({ whyNot }) => ({ interested: "no", whyNot }),
},
],
},
],
default: [
{
form: {
fields: () => ({ whyNotSure: ["", []] }),
render: ({ fields, back, next }) => (
<WhyNotSureForm fields={fields} back={back} next={next} />
),
},
},
{
return: ({ whyNotSure }) => ({ interested: "notSure", whyNotSure }),
},
],
},
},
];
export default function App() {
const onReturn = useCallback<OnReturn<Schema>>((output) => {
// | {
// interested: "yes";
// whyYes: string;
// }
// | {
// interested: "no";
// whyNot: string;
// }
// | {
// interested: "notSure";
// whyNotSure: string;
// }
console.log(output);
}, []);
return <Formity<Schema> flow={flow} onReturn={onReturn} />;
}
Each case function receives the flow values and returns a boolean. The then of the first case that returns true is executed, or default if none does.
In the Schema, each switch element has an s.Switch entry in struct, with the entries of the elements of each branch in branches, in the same order, and the ones of default.