hooks#useFormProgress TypeScript Examples

The following examples show how to use hooks#useFormProgress. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MultiStepFormBody.tsx    From frontend with GNU General Public License v3.0 5 votes vote down vote up
MultiStepFormBody = ({
  children,
  onNext,
  onBack,
  onSubmit,
  onCancel,
  title,
}: IMultiStepForm): JSX.Element => {
  const { trigger, watch, errors, clearErrors } = useFormContext();
  const { currentStep, goForward, goBack, goTo } = useFormProgress();

  const lastStep = React.Children.count(children) - 1;
  const steps = React.Children.toArray(children);
  const amountOfSteps = Array.from(Array(steps.length).keys());

  const formData = watch();

  const [form, setForm] = useState({});

  const handleSubmit = (data: IFormData): void => {
    if (_.isEmpty(errors)) {
      onSubmit(data);
    }
  };

  const updateCurrentForm = () => setForm((state) => ({ ...state, ...formData }));

  const handleNext = async () => {
    const status = await trigger();

    if (!status) return;

    updateCurrentForm();

    if (currentStep === lastStep) {
      handleSubmit({ ...form, ...formData });
      return;
    }

    goForward();
    clearErrors();
    onNext(formData);
  };

  const handleBack = () => {
    updateCurrentForm();

    goBack();
    onBack(formData);
  };

  return (
    <>
      {title && <StyledTitle>{title}</StyledTitle>}
      <ProgressBar
        activeStep={currentStep}
        steps={amountOfSteps}
        changeStep={goTo}
        formData={formData}
      />
      <StyledForm>{steps[currentStep]}</StyledForm>
      <ActionButtons
        lastStep={lastStep}
        activeStep={currentStep}
        onBack={handleBack}
        onNext={handleNext}
        onCancel={onCancel}
      />
    </>
  );
}