Flow elementsLoop

Flow elements

Loop

Learn how the loop element repeats elements of the flow while a condition is true.


Usage

The loop element repeats a set of flow elements while a condition is true.

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

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

import { QuestionForm } from "./components/question-form";

type Schema = {
  render: React.ReactNode;
  struct: [
    s.Variables<{
      i: number;
      questions: {
        question: string;
        options: { value: string; label: string }[];
        default: string;
        correct: string;
      }[];
      right: number;
      wrong: number;
    }>,
    s.Loop<
      [
        s.Variables<{
          question: {
            question: string;
            options: { value: string; label: string }[];
            default: string;
            correct: string;
          };
        }>,
        s.Form<{ answer: string }>,
        s.Variables<{ i: number; right: number; wrong: number }>,
      ]
    >,
    s.Return<{ right: number; wrong: number }>,
  ];
  inputs: Record<never, never>;
  params: Record<never, never>;
};

const flow: Flow<Schema> = [
  {
    variables: () => ({
      i: 0,
      questions: [
        {
          question: "What is the capital of Australia?",
          options: [
            { value: "sydney", label: "Sydney" },
            { value: "melbourne", label: "Melbourne" },
            { value: "canberra", label: "Canberra" },
          ],
          default: "sydney",
          correct: "canberra",
        },
        {
          question: "Who painted 'The Starry Night'?",
          options: [
            { value: "picasso", label: "Pablo Picasso" },
            { value: "vangogh", label: "Vincent van Gogh" },
            { value: "dali", label: "Salvador Dalí" },
          ],
          default: "picasso",
          correct: "vangogh",
        },
      ],
      right: 0,
      wrong: 0,
    }),
  },
  {
    loop: {
      while: ({ i, questions }) => i < questions.length,
      do: [
        {
          variables: ({ i, questions }) => ({
            question: questions[i],
          }),
        },
        {
          form: {
            fields: ({ question, i }) => ({
              answer: [question.default, [i]],
            }),
            render: ({ fields, values, back, next }) => (
              <QuestionForm
                key={values.i}
                fields={fields}
                question={values.question}
                back={back}
                next={next}
              />
            ),
          },
        },
        {
          variables: ({ i, question, answer, right, wrong }) => ({
            i: i + 1,
            right: question.correct === answer ? right + 1 : right,
            wrong: question.correct === answer ? wrong : wrong + 1,
          }),
        },
      ],
    },
  },
  {
    return: ({ right, wrong }) => ({ right, wrong }),
  },
];

export default function App() {
  const onReturn = useCallback<OnReturn<Schema>>((output) => {
    // {
    //   right: number;
    //   wrong: number;
    // }
    console.log(output);
  }, []);

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

The while function receives the flow values and returns a boolean. The elements in do are executed while it is true, and the flow continues after the loop when it is false.

In the Schema, each loop element has an s.Loop entry in struct, with the entries of the elements of do, in the same order as they appear in the flow.

A form inside a loop is the same form element in every iteration, so two things have to change between iterations. The rendered component needs a key that changes, like key={values.i}, so that React mounts a new form instead of reusing the previous one. The array of each field also needs a value that changes, like [i], so that the field starts from its default value instead of keeping the previous answer.