Basic conceptsState

Basic concepts

State

Learn what the state is about and how it can be used.


Overview

At any moment, a multi-step form has a state. It records which step the user is on, how they got there, and what they entered in every step so far. You can read the state, store it wherever you like, and hand it back to Formity later so the user picks up the form exactly where they left it.

There are three parts to the API:

  • getState: A function received by the form element's render function. It takes the current step's form values and returns the state of the multi-step form, without changing anything.
  • setState: A function received by the form element's render function. It takes a State and replaces the state of the multi-step form with it.
  • initialState: A value you can pass to the Formity component or the useFormity hook. The multi-step form starts from this state instead of from the first step.

The state is of type State, and the two functions are of type GetState and SetState.

You don't need to know what the state looks like inside. Get it from getState, store it, and pass it back unchanged. Two things to keep in mind:

  • The state can be stored with JSON.stringify as long as the flow values are JSON-serializable. Values such as Date or File need to be converted by you.
  • A saved state only works with the flow it was created from. If the flow changes between saving and resuming, discard the saved state.

Saving the state

To save the state as the user fills out the form, call getState inside your form component and persist it whenever the values change. Using React Hook Form, it could look like this:

TSX
const onSaveState = useEffectEvent(({ values }: { values: Values }) => {
  const state = getState(values);
  saveState(state);
});

useEffect(() => {
  const unsubscribe = form.subscribe({
    formState: { values: true },
    callback: onSaveState,
  });
  onSaveState({ values: form.getValues() });
  return () => unsubscribe();
}, [form]);

In this example, form comes from React Hook Form's useForm hook and Values is the type of the form values. The saveState function is not part of Formity. You write it yourself to store the state wherever you want, such as localStorage or a database.

Resuming the state

Pass the saved state to the initialState prop to resume the form from where the user left off.

TSX
return (
  <Formity<Schema> flow={flow} initialState={savedState} onReturn={onReturn} />
);