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

@codemask-labs/forms

v1.0.10-beta

Published

`codemask-labs/forms` is a continuation of old `react-form-builder-v2` package. Currenctly in **alpha** due to breaking changes and testing.

Downloads

391

Readme

codemask-labs/forms

codemask-labs/forms is a continuation of old react-form-builder-v2 package. Currenctly in alpha due to breaking changes and testing.

New features:

  • less code
  • less re-renders
  • zod schemas for validation
  • uses stan-js underneath

Basic usage

  1. Start with schema definition. It can be placed inline or in separate file (as a hook):
import z from 'zod'

const useOTPFormSchema = () => {
   const phoneNumber = z
      .string()
      // chain your validation logic
      .length(9, {
         // override default zod validation messages
         message: 'Phone number must have 9 digits'
      })
      .default('')

   const otpCode = z
     .string()
     .optional() // mark field as optional
     .default('123456') // set default values eg. when you want to prefill the form, must be called at the end of the chain

   return {
       phoneNumber,
       otpCode
   }
}
  1. Define useForm:
const App = () => {
    const { form, submit, isValid } = useForm({
        fields: useOTPFormSchema(),
        onSuccess: ({ phoneNumber, otpCode }) => {
           // form is valid!
        },
        onError: errors => {
           // form is invalid!
        }
    })

    return (
        <form
            onSubmit={event => {
                event.preventDefault()
                submit()
            }}
        >
            <Input field={form.name} />
            <Input field={form.email} />
            <button disabled={!isValid}>
                Submit
            </button>
        </form>
    )
}
  1. Pass field to your form components:
const Input: React.FunctionComponent<{ field: ReactiveFormField<string> }> = ({ field: useField }) => {
    const { value, onChange, reset, error, validate } = useField()

    return (
        <div>
            <input
                 value={value}
                 onChange={event => onChange(event.target.value)}
                 onBlur={() => validate()}
             />
            <span>{error}</span>
            <button
                type='button'
                onClick={reset}
             >
                  Reset
            </button>
        </div>
    )
}

[!WARNING]
If you use React Compiler, make sure you rename field to useField - otherwise entire hook will be memoized and won't update the state


API

useForm

| prop | type | functionality | |----------|-------------|------| | form | Record<string, ReactiveFormField<any>> | all fields that should be passed to corresponding components | | submit | () => void | Submit the form | | reset | (...args?: Array<string>) => void | resets either entire form or specific fields | | getValues | () => Record<string, any> | Returns your form values as object | | isValid | boolean | Defines if your form is valid | | updateForm | (fields: Partial<Record<string, Partial<FormField<any>>>) => void | stanjs method to update form state | | useFormEffect | (fields: Record<string, any>) => void | stanjs effect - function that allows to subscribe to store's values change |

useForm config

| prop | type | functionality | |----------|-------------|------| | fields | Record<string, ZodDefault<any>> | zod based schema for your form | onSuccess | (fields: Record<string, any>) => void | called when your form is valid | | onError | (errors: Record<string, string>) => void | called when form is not valid, returns a pair for field key and error message | | onSubmit | (fields: Record<string, any>) => void | called after the validation, but before onSuccess or onError, useful for additonal validation like dependent fields |

field (ReactiveFormField<any>>)

| prop | type | functionality | |----------|-------------|------| | error | string | field error message passed from zod | | hasError | boolean | defines if your field has error | | value | any | current field value | | onChange | (value: any) => void | function to update current field value | | reset | () => void | resets current field to defaults | | validate | () => void | should be called to validate the field eg. onBlur event

Notes

If you want to dynamically set field as optional you can either conditionally return different schemas, or create yourself simple util to do this:

export const dynamicOptional = <TSchema extends z.ZodDefault<z.ZodTypeAny>>(schema: TSchema, optional?: boolean) =>
    optional ? schema.optional().default(schema._def.defaultValue()) : schema