@bedrockstreaming/form-context
TypeScript icon, indicating that this package has built-in type declarations

0.9.2 • Public • Published

form-context

form-context is a React reducer solution to manage steps.

❓ Why

Since we are using react-hook-form to persist data locally, we are only storing the form data and step information on each step submission.

:::note

You can avoid to store any form data if you wish

:::

🏗️ Install

npm install @bedrockstreaming/form-context

🚀 Usage

import { useEffect } from 'react';
import { FormBuilder } from '@bedrockstreaming/form-builder';
import {
  getCurrentStepIndex,
  isLastStep,
  resetForm,
  initForm,
  setNextStep,
  useFormsDispatch,
  useFormsState,
  FormProvider,
} from '@bedrockstreaming/form-context';

import { schema, formId } from './path/to/my/config';
import { fooSubmitAction } from '<my-app-module>';

const FooForm = () => {
  const dispatch = useFormsDispatch();
  const state = useFormsState();
  const currentStepIndex = getCurrentStepIndex(formId)(state);
  const shouldSubmit = isLastStepSelector(formId)(state);
  const previousValues = getFormData(formId)(state);

  useEffect(() => {
    dispatch(initForm(formId, schema));
  }, [dispatch]);

  const handleSubmit = useSubmit(formId);

  const handleNextStep = (fieldsValues: FieldValues) => {
    dispatch(updateFormData(formId, fieldsValues));
    dispatch(setNextStep(formId));
  };

  const handleSubmit = (fieldValues: FieldValues) => {
    if (shouldSubmit) {
      fooSubmit(fieldValues);
      dispatch(resetForm(formId));
    } else {
      dispatch(setNextStep(formId));
    }
  };

  return (
    <FormBuilder
      dictionary={dictionary}
      schema={schema}
      onSubmit={handleSubmit}
      handleNextStep={handleNextStep}
      currentStepIndex={currentStepIndex}
    />
  );
};

export const FormContainer = () => {
  return (
    <FormsProvider>
      <Form />
    </FormsProvider>
  );
};

Running unit tests

Run nx test form-context to execute the unit tests via Jest.

Readme

Keywords

none

Package Sidebar

Install

npm i @bedrockstreaming/form-context

Weekly Downloads

12

Version

0.9.2

License

none

Unpacked Size

65.7 kB

Total Files

9

Last publish

Collaborators

  • tetsu9901
  • jsulpis
  • martinschneider01
  • jcoquet
  • fdubost
  • slashgear
  • hpierre74
  • nbazille