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

use-form-state

v0.0.6

Published

React hook for managing form and input state and form validation.

Downloads

434

Readme

Current release GitHub license GitHub pull-requests GitHub issues

Getting Started

To get it started, add use-form-state to your project:

npm install --save use-form-state

Please note that use-form-state requires react@^16.12.0 as a peer dependency.

Examples

Basic Usage

import useFormState from 'use-form-state'

export const LoginForm = ({ onSubmit }) => {
    const { getNativeInputProps } = useFormState()

    return (
        <form onSubmit={onSubmit}>
            <input {...getNativeInputProps('email')} required />
            <input {...getNativeInputProps('password')} required />
        </form>
    )
}

From the example above, as the user submits the form, the formState object will look something like this:

{
    values: {
        email: '[email protected]',
        password: '123456789',
    },
    errors: [],
    isDirty: true
    isValid: true,
    isPristine: false,
    setValues: Function,
    handleChange: Function,
    handleNativeChange: Function,
    validate: Function,
    updateErrors: Function,
    resetForm: Function,
    getInputProps: Function,
    getNativeInputProps: Function,
    valuesToInput: Function,
    getValue: Function,
    getErrorMessages: Function,
    hasError: Function,
}

API

useFormState

import useFormState from 'use-form-state'

export const FormComponent = () => {
    const {
        values,
        errors,
        isDirty,
        isValid,
        isPristine,
        setValues,
        handleChange,
        handleNativeChange,
        validate,
        updateErrors,
        resetForm,
        getInputProps,
        getNativeInputProps,
        valuesToInput,
        getValue,
        getErrorMessages,
        hasError,
    } = useFormState(initialValues, formOptions)
    return (
        // ...
    )
}

initialValues

useFormState takes an optional initial values object with keys as the name property of the form inputs, and values as the initial values of those inputs.

formOptions

useFormState also accepts an optional form options object as a second argument with following properties:

formOptions.validation

Function that returns an array of validators created by createFormValidation

Example: See return value of createFormValidation

Default: empty array

formOptions.validationOptions

Adds extra options that can be used in the validation. See validate.validationOptions for more info

Example:

const isCompany = user.type === 'company'

const formState = useFormState(initialValues, {
    validationOptions: {
        isCompany,
    }
})

Default: empty object

formOptions.valuesToInput

Function that can be used to manipulate the values used in the form state before submitting the form. This can be useful when the name of the input field differs from the API or when you need to parse/format dates for example.

Example:

const formState = useFormState(initialValues, {
    valuesToInput: ({
        firstName,
        birthDate,
        ...otherValues,
    }) => ({
        ...otherValues,
        first_name: firstName,
        birth_date: birthDate.toISOString(),
    })
})

Default: values from state

formOptions.debug

When set to true, useFormState will log its state to the console when changes are made.

Default: false

values

errors

isDirty

isValid

isPristine

setValues

handleChange

handleNativeChange

validate

updateErrors

resetForm

getInputProps

getNativeInputProps

valuesToInput

getValue

getErrorMessages

hasError

createFormValidation

import useFormState, { createFormValidation } from 'use-form-state'

export const FormComponent = () => {
    const formState = useFormState(initialValues, {
        validation: createFormValidation([{
            path: 'firstName',
            validate: (name) => name !== '',
            message: 'First name is required!',
        }, {
            path: 'birthDate',
            validate: (date) => date > new Date(),
            message: 'Date must be after now.',
        }, {
            path: 'vatNumber',
            validate: (vatNumber, values, { isCompany }) => (
                isCompany && vatNumber !== ''
            ),
            message: 'VAT number is required for a company.',
        }])
    })
    return (
        // ...
    )
}

path

Required

path references the name to the value in the formState where you want to add the validation on.

validate

Required

Function that validates the given value and returns the result of the expresion.

validate.currentValue

The first argument of validate is the value from the formState based on the given path.

validate.allValues

Second argument includes all the values from the formState.

validate.validationOptions

validationOptions is an optional argument you can use as external "dependency" for your validation expression.

message

The message you want to display near the form input to show the user what went wrong.

Default: 'Invalid'

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Authors

See also the list of contributors who participated in this project.

About us

Wappla BVBA We shape, build and grow ambitious digital products.

License

This project is licensed under the MIT License - see the LICENSE.md file for details