@muzikanto/observable-form

Form state manager

Usage no npm install needed!

<script type="module">
  import muzikantoObservableForm from 'https://cdn.skypack.dev/@muzikanto/observable-form';
</script>

README

Observable-form

npm version downloads dependencies Status size Code style

Introduction

Installation

npm i @muzikanto/observable @muzikanto/observable-form
# or
yarn add @muzikanto/observable @muzikanto/observable-form

Examples

demo

example code example with hooks code

create api

interface State {
   text: string;
   field: string;
   deep: {
      one: string;
      two: string;
   };
   arr: string[];
}

const validationSchema = Yup.object().shape({
   text: Yup.string()
      .required()
      .max(5),
   field: Yup.string()
      .required()
      .max(3),
});

const form = createForm<FormState>({
   validateOnMount: false,
   initialState: {
      text: '123',
      field: '',
      deep: { one: '1', two: '' },
      arr: ['1', '2', '3'],
   },
   validationSchema,
});

form.values.watch(state => console.log('values: ', state));

create field

function FieldInput(props: { name: string }) {
   const { value, error, touched, setFieldTouched, setFieldValue } = useField<string>({
      name: props.name,
      validate: v => {
         if (false) {
            return 'my custom error';
         }
      },
   });

   const touchedAndError = Boolean(touched && error);

   return (
      <>
         <input
            value={value}
            onChange={e => setFieldValue(e.target.value)}
            onBlur={() => setFieldTouched(true)}
         />
         {touchedAndError && <span>{error}</span>}
      </>
   );
}

Use

function FormComponent() {
   return (
      <Form
         form={form}
         formId='form-id'
         formProps={{}}
         Confirm={({ open, onClose, onAccept }) => (
            <Dialog open={open} onClose={onClose}>
               <DialogContent>
                  <Button
                     onClick={() => {
                        onClose();
                        form.reset();
                     }}
                  >
                     Reject
                  </Button>
                  <Button onClick={onAccept}>Accept</Button>
               </DialogContent>
            </Dialog>
         )}
      >
         <FieldInput name='text' />
         <FieldInput name='field' />
         <FieldInput name='deep.one' />

         <button onClick={() => form.reset()}>RESET</button>
         <button onClick={() => form.validate()}>VALIDATE</button>

         <Submit
            component={({ onClick, disabled }) => (
               <button onClick={onClick} disabled={disabled}>
                  Submit
               </button>
            )}
         />
         <ErrorMessage name='field' component={props => <span {...props} />} />
      </Form>
   );
}

License

MIT