npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@bscop/use-form

v2.1.0

Published

A custom React hook handle form.

Downloads

8

Readme

@bscop/use-form

GitHub license npm version CircleCI Status Coverage

A custom React hook handle form.

View in Storybook.

Install

npm i @bscop/use-form

Usage

import useForm from "@bscop/use-form";

function App () {
  const { onSubmit, pending, register } = useForm(
    {
      email: {
        label: "Email",
        schema: [
          {
            id: "required",
          },
        ],
      }
    }
  );

  const send = 
    (payload) => {
      fetch("/", { method: "POST", body: JSON.stringify(payload) })
        .then(
          () => {
            // ...
          }
        )
    };

  return (
    <form onSubmit={onSubmit(send)}>
      <div>
        <label>
          Email:
          <input {...register("email", { type: "email" })}/>
        </label>
      </div>
      <button disabled={pending} type="submit">Save</button>
    </form>
  );
}

API

const {
  debug,
  errors,
  forceValue,
  pending,
  onSubmit,
  register,
  resetForm,
  unregister,
  valueOf,
} : HookResult = useForm(config: FormConfig);

FormConfig

When executing useForm we pass to an object to configure the form.
FormConfig is an object whose keys correspond to name of inputs present in the form, and values contains the configuration for each field (Field).

const fieldEmailConfig : Field = {
  schema: [
    {
      id: "required",
    },
  ]
};

const fieldPasswordConfig : Field = {
};

const formConfig : FormConfig = {
  email: fieldEmailConfig,
  password: fieldPasswordConfig,
}

useForm(formConfig);

Each field may have following configuration properties:

  • defaultValue ([string]) : it's used as initial value, and after the form is reset, or the field in unregistered.

  • label (string) : it's used to reference the field in validation error message.

  • schema ([Rule[]]) : it specifies the rules the field value must respect - more on this subject later.

  • value ([string|string[]]) : it specifies the initial value of the field - it can be a list of values to accomodate for the possibility of checkbox, and select to have multiple value selected at the same time.

Validation schema

It's a list of validation the field value must pass in order to be considered valid. Each validation validation rule must have an id field that matches the name of a built-in rule.

Built-in rules are:

  • required : { id: "required" }.
  • max length : { id: "maxlen", attrs: { size: number } }.
  • min length : { id: "minlen", attrs: { size: number } }.
  • format : { id: "format", attrs: { regexp : string} }.
  • range : { id: "range", attrs: { range : number[] } }.
  • date : { id: "date" }.
  • one of : { id: "oneof", attrs: { options : string[] } }.

Each rule can optionally also specify a message to override the default message; eg.

useForm(
  {
    name: {
      schema: [
        {
          id: "required",
          message: "Did you forget something?",
        },
      ]
    }
  }
)

It's also possible to specify a custom validation rule inline; eg.

useForm(
  {
    name: {
      schema: [
        {
          validate (
            name : string,
            label : string,
            value : string|string[],
            rule : Rule,
            formState : unknown
          ) : undefined|string {
            /**
             * Returns undefined when field value is valid;
             * otherwise return a string describing the error.
             * This string is meant to be rendered as validation error
             * below the field.
             */
            const isValid = computeIsValid(value);

            if (isValid) {
              return undefined;
            }

            return "The value is not valid.";
          }
        }
      ]
    }
  }
)

HookResult

useForm returns an object with the following properties:

  • debug (() => void) : print the state of the form.

  • errors (null | Record<keyof FormConfig, string>) : contains validation error for each field in the form; it's null if the form is valid (or validation didn't run yet).

  • forceValue ((name : string, value : string|string[]) => void, shouldValidate ?: boolean) : programatically set the value of a field, and trigger validation.

  • valueOf ((name : string) => string|string[]) : return the value of a given field; for checkbox, and select[multiple] it returns a list of values.

  • pending (boolean) : it is true if the submit is in progress - it is recommended to use it to mark the submit button as disabled.

  • onSubmit ((handler : Record<keyof FormConfig, string>) => (event : React.FormEvent) => void) : handles the submit of the form - the actual request is executed by the handler defined in user-land.

  • register ((name : string, attrs ?: Record<string, string>) => FieldAttributes) : returns the attributes needed to control the field.

import useForm from "@bscop/use-form";

function App () {
  const { onSubmit, pending, register } = useForm(
    // ...
  );

  const send = (payload) => {};

  return (
    <form onSubmit={onSubmit(send)}>
      <div>
        <label>
          Email:
          <input {...register("email", { type: "email" })}/>
        </label>
      </div>
      <button disabled={pending} type="submit">Save</button>
    </form>
  );
}
  • resetForm (() => void) : reset the value of all the fields.

  • unregister ((name : string) => void) : reset the state of one (or many) form field that becomes unnecessary.

Contribute

Read the guidelines.

Run tests

npm test

Coverage

Coverage reports are hosted on codecov.

npm run badge:coverage -- --token=<guid>

Bruno Scopelliti
www.brunoscopelliti.com