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

@andydowell/use-form-state

v2.0.2

Published

A React hook for managing form state and validation

Downloads

247

Readme

FormState React Hook

The useFormState hook is a utility for managing form state in React applications. It provides functionality for tracking and validating form fields, as well as extracting form data in different formats. With useFormState, you can easily handle form interactions and ensure data integrity.

Installation

To install the use-form-state package, run the following command:

npm install @andydowell/use-form-state

Usage

Initializing the Form State

import { useFormState } from "@andydowell/use-form-state";

const formState = useFormState(formFieldParams, options);

Before using the hook, you need to define the formFieldParams. These props represent the structure of your form and include information such as default values, validation rules, and error messages.

Each field in the formFieldParams is defined by a key-value pair, where the key is the name of the field and the value is an object with the following properties:

| Property | Description | Type | Example | | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- | | defaultValue | The default value for the form field. | | "" | | required | (Optional) Specifies whether the form field is required. | { message: string } | { message: "Please enter your email address" } | | validation | (Optional) An object that defines custom validation rules for the form field. Each rule is represented by a key-value pair, where the key is the name of the rule and the value is an object with validator and message properties. | {[key]: {validator: (value, state) => boolean, message: string}} | { longerThanOneChar: { validator: value => value.length > 1, message: 'Password must be longer than 1 character' } } | | label | (Optional) Default as empty string (""). | string | 'Email' | | helperText | (Optional) Text that provides additional information or guidance for the form field. | string | 'Please enter a valid email' |

The second parameter options is an object with the following properties:

| Property | Type | Description | | ------------------------- | ------ | --------------------------------------------------------------------------------------------- | | errorUpdateDelayInSeconds | number | (Optional) Specifies the delay in seconds before the error type is updated. Default is 0.5. |

You can see an example of formFieldParams and options in the Example section.

API

The useFormState hook returns an object with the following properties and methods:

const { state, set, checkIfAllValid, extractStateValue, reset } = useFormState(formFieldParams, options);

The state object contains the current values and validation status of each form field. The set function allows you to update the form field values. The checkIfAllValid function checks if all fields are valid. The extractStateValue function extracts the form data in the specified format. The reset function resets the form to its initial state.

Form State

Each form field in the state object is represented by an object with the following properties:

| Property | Description | Example Usage | Example Output | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | value | The current value of the form field. | state.email.value | | isValid | Indicates whether the value of the form field is valid. Required fields are considered valid if they are filled. If validation param is provided, the value will be validated against the validator functions inside. | state.email.isValid | | isInteracted | Indicates whether the form field has been interacted with (user has changed the value). | state.email.isInteracted | | isRequired | Indicates whether the form field is required. | state.email.isRequired | | label | The label of the form field. | state.email.label | 'Email' | | helperText | A helper text that provides additional information or instructions for the form field. | state.email.helperText | | error | An object that represents an error associated with the form field. It has two properties: type (the type of error) and message (the error message). If there is no error, this property will be undefined. | state.email.errorstate.email.error?.typestate.email.error?.message | { type: "required", message: "Please enter your email address" } |

error is not updated immediately when the value of a form field changes. Instead, it is updated after a delay (default is 0.5 seconds) to prevent the error message from flashing when the user is typing. If the field is not interacted with, the error will not be updated. Running checkIfAllValid({ updateErrorType: true }) will update all errors immediately.

Updating Form Field Values

To update a form field value, use the set function:

set(key, value, setInteracted);

| Parameter | Type | Description | Example | | --------------- | ------------------------- | ----------------------------------------------------------------------------------------- | ----------------------- | | key | string | The key of the field in the form state. | 'email' | | value | (type of the field value) | The new value to be set for the field. | '[email protected]' | | setInteracted | boolean | (Optional) Indicates whether the field should be marked as interacted. Default is true. | false |

You can see an example of set in the Example section.

Checking Form Field Validity

You can check the validity of individual form fields by accessing the isValid property in the state object:

const isEmailValid = state.email.isValid;

Checking Overall Form Validity

To check if the entire form is valid, use the checkIfAllValid function:

const isFormValid = checkIfAllValid(options);

The options parameter is an object with the following properties:

| Parameter | Type | Description | | ----------------- | ------- | ------------------------------------------------------------------------------------------------ | | updateErrorType | boolean | (Optional) Specifies whether the error types of all fields should be updated. Default is true. |

The validation will check all form fields based on their defined rules and update their validation status and error messages accordingly. You can see an example of checkIfAllValid in the Example section.

Extracting Form Data

You can extract the form data in different formats using the extractStateValue function. Currently, two formats are supported: 'object' and 'formdata'.

Example: To extract the form data as an object:

const dataObject = extractStateValue({ format: "object" });

To extract the form data as FormData:

const formData = extractStateValue({ format: "formdata" });

You can see an example of extractStateValue in the Example section.

Resetting the Form

To reset the form to its initial state, use the reset function:

reset();

This will clear all form field values and reset their validation status. You can see an example of reset in the Example section.

Example

const newUser = useFormState({
  email: {
    defaultValue: "@",
    helperText: "Your Email Address",
    required: { message: "Please enter your email address" },
    validation: {
      longerThanOneChar: {
        validator: value => value.length > 1,
        message: "Email address must be longer than 1 character",
      },
      ["has-add-sign"]: {
        validator: value => value.includes("@"),
        message: "Email address must contain '@'",
      },
    },
  },
  password: {
    defaultValue: "",
    helperText: "Your Password",
    required: { message: "Please enter your password" },
    validation: {
      longerThanOneChar: {
        validator: value => value.length > 1,
        message: "Password must be longer than 1 character",
      },
    },
  },
  confirmPassword: {
    defaultValue: "",
    helperText: "Confirm Your Password",
    required: { message: "Please enter your password again" },
    validation: {
      longerThanOneChar: {
        validator: value => value.length > 1,
        message: "Password must be longer than 1 character",
      },
      matchPassword: {
        validator: (value, state) => value === state.password.value,
        message: "Passwords do not match",
      },
    },
  },
});

// ---------------------------------

const onSubmit = async e => {
  e.preventDefault();
  if (!newUser.checkIfAllValid()) return;

  const formdata = newUser.extractStateValue({ format: "formdata" });
  // ... Submit formdata to server
};

// ---------------------------------

const { email, password, confirmPassword } = newUser.state;

<form onSubmit={onSubmit}>
  <div>
    <Input value={email.value} onChange={e => newUser.set("email", e.target.value)} />
    <p>{email.error?.message || email.helperText}</p>
  </div>
  <div>
    <Input type="password" value={password.value} onChange={e => newUser.set("password", e.target.value)} />
    <p>{password.error?.message || password.helperText}</p>
  </div>
  <div>
    <Input
      type="password"
      value={confirmPassword.value}
      onChange={e => newUser.set("confirmPassword", e.target.value)}
    />
    <p>{confirmPassword.error?.message || confirmPassword.helperText}</p>
  </div>
  <button type="submit">Submit</button>
  <button type="reset" onClick={newUser.reset}>
    Reset
  </button>
</form>;

License

This package is open source and available under the MIT License.