Julia
Julia

Reputation: 1

Multistep dynamic form with react-hook-form where fields and validation rules are fetched from server

I'm building a multistep form where I have 3 steps:

  1. user inputs fills the fields, validation happens, if ok goes to the next step
  2. fetching fields and rules from server based on data from step1, I don't know what fields to expect beforehand or how many, they should ge generated on the fly and appended to the form
  3. just final confirmation

I'm having trouble to make the architecture for such form where I don't know what fields to expect on the second step and how to type it? I used zod schema for first step but then I realized it's not suitable for me because I don't know what fields to expect and I can't change validation schema on the fly (?)

I was thinking about having 3 separate forms for each step and manage their own state like react-hook-form does in wizard form https://react-hook-form.com/advanced-usage#WizardFormFunnel. But this solution feels odd for my case, I don't have separate routes for each step if user reloads the page, they will loose the data and will go to step 1 and it's expected

I have several questions:

  1. How would you recommend to build form where some fields, its configs are fetched from the server?
  2. How do I provide types for the form if I don't know what fields would come on the second step (they can be generated only on the second step)?
  const { register, control, } = useForm<Inputs>({ defaultValues: PAYMENT_DEFAULT_VALUES, });

Upvotes: 0

Views: 153

Answers (0)

Related Questions