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

@zecos/fields

v0.0.0

Published

form fields state management

Downloads

12

Readme

fieldz

fieldz is a form state management tool that should integrate well with

It's a minimalistic library with only ~90 LoC and follows functional programming pattern.

It's also heckin' easy to use.

The first step is to declare your field properties:

import { nameValidator } from "validatorz"

const fieldProperties = {
  firstName: {
    init: "",
    validate: nameValidator
  },
  customField: {
    validate: (val: string) => {
      if (val !== "hello") {
        return [new Error("value must be hello!")]
      }
      return []
    },
    init: "this is my init value"
  }
}

Field properties consist of two values:

  • init: initial value for the field
  • validate: validation function that returns array of errors

This library is designed to integrate well with validatorz, but you can feel free to use whatever validation functions you want like in customField.

Next, we instantiate our fieldz™ using the fieldz function:

import { fields } from 'fieldz'
// fieldProperties

const { getState } = fields(fieldProperties)
const state = getState()

You can see fields returns a function called getState.

getState does just what it sounds like: gets state.

state is the initial state of our fields. It's just data.

For our field properties, it would be something like this:

{
  firstName: {
    errors: [],
    touched: false,
    pristine: true,
    value: ''
  },
  customField: {
    errors: [],
    touched: false,
    pristine: true,
    value: 'this is my init value'
  }
}

There are 4 state properties

  • errors: their array of errors (possibly empty) based on the current value
  • value: their current value
  • touched: boolean: whether they have been "touched" or not (the value has been adjusted, and the input has lost focus)
  • pristine: a boolean value indicating whether or not the fields have been

Quite simple, but how do we manipulate state?

Well, for that, we'll turn to our actions:

const { getState, ...actions } = fields(fieldProperties)
const { setValue, setValues, setTouched, resetField, resetFields, setState } = actions

Each action adjusts state and then returns the new state:

  • setValue:
    • takes a key and a value
    • validates the data sets errors to any returned errors from the validator
    • sets pristine to false if not already set
  • setValues:
    • takes a map of key values
    • performs everything setValue does
  • setTouched: sets field's touched property to true if not already set
  • resetField: sets a field's properties to their original value
  • resetFields: same as resetField, but for all fields
  • setState:
    • sets the internal fields state
    • hopefully, you'll never need this

But enough of the theory, let's see it in action.

With large chunks of code omitted, you could see something like this:

import { fields } from 'fieldz'
import { nameValidator } from "validatorz"

const fieldProperties = {
  firstName: {
    errors: [],
    touched: false,
    pristine: true,
    value: ''
  },
  customField: {
    errors: [],
    touched: false,
    pristine: true,
    value: 'this is my init value'
  }
}

const Form = () => {
  const [[actions, formState], _setFormState] = useState(() => fields(fieldProperties))
  const { setValue, setValues, setTouched, resetField, resetFields, setState } = actions
  const setFormState = state => _setFormState([actions, state])

  return (
    <form>
      {Object.entries(formState)
        .map(([fieldName, {errors, value, touched, pristine}]) => (
          <div>
            {(touched && errors.length) ? <span className="input-error">{errors.map(err => <div>{err.toString()}</div>)}</span> : ""}
            <label for={fieldName}>{camelToTitle(fieldName)}</label>
            <input
              name={fieldName}
              value={value}
              onChange={e => setFormState(setValue(fieldName, e.target.value))}
              onBlur={_ => setFormState(setTouched(fieldName))}
            />
          </div>
        ))
      }
    </form>
  )
}

This is made much easier now with react-fieldz, so be sure to check that out.

In addition, you can now just import one field by using the field function, like so:

import { field } from 'fieldz'
import { nameValidator } from 'validatorz'

const firstName = field({
  init: "",
  validator: nameValidator,
})