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

@nutgaard/use-formstate

v3.0.1

Published

A react-hook for managing form values, errors and more

Downloads

54

Readme

UseFormstate

styled with prettier Travis Dev Dependencies

A react-hook for managing form values, errors and more

Usage

Preparations

The form-shape and how it should be validated is defined using the useFormstate function. Optimally this should be outside of your react-component.

type FormData = { // Don't use an interface here. Read me under "known issues"
  name: string;
  city: string;
  hobby: string;
}

interface FormProps {
  validate: boolean;
}

const initialState: FormData = {
  name: '',
  city: '',
  hobby: ''
};

const validator = useFormstate<FormData, FormProps>({
  name: (value) => value.length > 256 ? 'Thats a might long name' : undefined,
  city: (value, values, props) => {
     if (props.validate) {
       return value.length === 0 ? 'Must provide a city' : undefined
     }
     return undefined;
  },
  hobby: (value, values, props) => {
     if (values.city.length > 0 && props.validate) {
       return value.length === 0 ? 'Hobby is required if city is provided' : undefined
     }
     return undefined;
  }
});

As an alternative you may pass a function instead of an object to useFormstate. This may useful in instances where form-elements are conditonally-validated, though the two approaches are functionally equivalent.

const validator = useFormstate<FormData, FormProps>((values, props) => {
  const name = values.name.length > 256 ? 'Thats a might long name' : undefined;
  const city = props.validate && values.city.length === 0 ? 'Must provide a city' : undefined;
  const hobby = values.city.length > 0 && props.validate && values.hobby.length === 0 ? 'Hobby is required if city is provided' : undefined;

  return { name, city, hobby };
});

Use it

function submithandler(values: FormData) {
    return fetch('...Do your thing...');
}

function MyForm(props: Props) {
  const state: Formstate<FormData> = validator(initialState);
  
  return (
    <form onSubmit={state.onSubmit(submithandler)}>
      <label htmlFor={state.fields.name.input.id}>Name:</label>
      <input {...state.fields.name.input} />
      {state.field.name.error ? <span>state.field.name.error</span> : undefined}

      <label htmlFor={state.fields.city.input.id}>City:</label>
      <input {...state.fields.city.input} />
      {state.field.city.error ? <span>state.field.city.error</span> : undefined}

      <label htmlFor={state.fields.hobby.input.id}Name>Hobby:</label>
      <input {...state.fields.hobby.input} />
      {state.field.hobby.error ? <span>state.field.hobby.error</span> : undefined}

      <button type="submit" disabled={state.submitting}>Save</button>
    </form>
  );
}

Types

Most notable types are Formstate<S> and FieldState:

Formstate

The returntype of calling useFormstate(validation)(initialValues, props);

submitting: boolean;                // is the submithandler current running
pristine: boolean;                  // is 'values === initialValues'
valid: boolean;                     // is the form as a whole valid, e.g no errors
errors: { fieldnames: string };     
fields: { fieldnames: FieldState }

FieldState

The type containing information for each field.

pristine: boolean;                  // is 'values === initialValues'
touched: boolean;                   // has this element had focus
initialValue: boolean;              // initialValue as specified 
error?: string;                     // this elements error if any 
input: {
  id: string;                       
  name: string;
  value: string;
  onChange: ChangeEventHandler;
  onBlur: FocusEventHandler;
};                      

Known issues

interface vs type

Its recommended to use type insteadof interface when defining your form-shape. E.g

// DON'T DO THIS
interface FormShape {
  name: string;
}

// DO THIS
type FormShape = {
  name: string;
}

The underlying issue can be better understood by read through this official issue; https://github.com/microsoft/TypeScript/issues/15300

Credits

Made using the awesome typescript library starter