@zecos/fieldz
TypeScript icon, indicating that this package has built-in type declarations

0.0.8 • Public • Published

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,
})

Package Sidebar

Install

npm i @zecos/fieldz

Weekly Downloads

1

Version

0.0.8

License

ISC

Unpacked Size

35.6 kB

Total Files

21

Last publish

Collaborators

  • zwhitchcox