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

react-redux-easy-form

v2.0.0

Published

Form hooks for react applications with ability to configure fields and validate theirs values

Downloads

14

Readme

react-redux-easy-form

npm version npm downloads

Main Concepts:

  1. Form has to perform in redux-middleware layer, not in components.
  2. Total dividing application views and business-logic.
  3. Minimum subscriptions and render processes.
  4. Maximum usability.
  5. Including modern React concepts.
  6. Static types (TypeScript).
  7. Performs in ReactDOM and ReactNative environments both

Installation

npm i react-redux-easy-form --save

You need react, redux, react-redux, reselect also to be installed.

Configuring redux-store

import { applyMiddleware, createStore, combineReducers } from 'redux';
import { easyFormMiddleware, easyFormReducer } from 'react-redux-easy-form';

const rootReducer = combineReducers({
   forms: easyFormReducer,
   // ... your reducers
});

const mws = applyMiddleware(
  easyFormMiddleware,
  // your middlewares
);

const store = createStore(rootReducer, {}, mws);

Initiate Form

import { FormProvider } from 'react-redux-easy-form';
// if use TS, the author will recommend to use enums for forms and fields naming
import { EFormName } from '@src/root-enums';

const ProfileForm = memo(() => {
   const dispatch = useDispatch();

   const initialValues = useSelector(getProfileFormInitialValues);

   useEffect(() => {
      dispatch(fetchInitialData());
   }, []);

   return (
      <FormProvider
        initialValues={initialValues}      
        name={EFormName.Profile}
      >
        <AgeField/>
        <FullNameField />
        <GenderField />
      </FormProvider>
   );
});

The fields will be bound with form name by React Context API.

Note: FormProvider does not create an element wrapper like form or kind. In this way FormProvider can be used in ReactDOM or ReactNative environment. If you need semantic wrapper, wrap the provider in form-element by yourself.

Note: Form component is deprecated since v2.0.0.

Implement Form Fields

Define Field Config

import { IFieldConfig } from 'react-redux-easy-form';

const fieldConfig: IFieldConfig = {
  changeValueGetter: (event) => event.target.value,
  validateOnChange: true,
  validators: [
     (value) => Number(value) > 99 ? 'Must be less than 100' : null,
  ],
};

IFieldConfig

| Option Name | Option Type | Description | | --- | --- | --- | | changeValueGetter | (event:any)=>any | A callback, that calls in onChange callback-prop, and transforms input argument into output result to set | | validateOnChange | boolean | A boolean flag, which decides to call fieldValidator on each onChange call to immediately receive validation result | | validators | TValidator[] | An array of TValidator functions, that validates the field separately. Each validation result will be set as separate element of output array |

Call useField Hook Within Your Component

import { useField } from 'react-redux-easy-form';

const AgeField = memo(() => {
  const {
    errors,
    onChange,
    value,
  } = useField<string>(EProfileFieldName.Age, fieldConfig);

  return (
    <div>
      <label htmlFor={EProfileFieldName.Age}>
        Age (years)
      </label>
      <input
        name={EProfileFieldName.Age}
        onChange={onChange}
        type="number"
        value={value ?? ''}
      />
      {errors && (
        <ul>
          {errors.map((err: string) => (
            <li key={atob(err)} style={{ color: 'red' }}>{err}</li>
          ))}
        </ul>
      )}
    </div>
  );
});

useField hook returns an object of type TUseFieldSubscription.

TUseFieldSubscription

| Name | Type | Description | | --- | --- | --- | | clear | () => void | A callback, clearing the field value in redux-store | | errors | string[], null | An array of field errors, provided after the validators called | | isFieldValid | boolean | A boolean value defines that field validation completed with no errors | | isPristine | boolean | A boolean value shows that field has had no changes | | onChange | (...callbackArgs: any[]) => void | A callback, changing value of an input in redux store | | validate | () => void | A callback, triggering the validation process of the field. For example, you can put it in onFocus, or onBlur props of your input | | value | any | Current value of the field in forms state of redux store |

Action-Creators

Action-Creators starting the middleware

changeValue

changeValue(formName: string, fieldName: string, value: any): Action

Starts a middleware changing form field value. Field status becomes dirty.

changeValueAndValidate

changeValueAndValidate(formName: string, fieldName: string, value: any): Action

Starts a middleware changing form field value and immediately calls the validator on it.

clearValue

clearValue(formName: string, fieldName: string): Action

Starts a middleware clearing the field value. Status becomes dirty.

validateAll

validateAll(formName: string): Action

Starts a middleware launching all validators in the form.

validateField

validateField(formName: string, fieldName: string): Action

Starts a middleware launching all validators for the field.

Flat Action-Creators

clearFieldErrors

clearFieldErrors(formName: string, fieldName: string): Action

Sets the field errors to null

clearFieldValue

clearFieldValue(formName: string, fieldName: string): Action

Sets the form field value to null

initiateForm

initiateForm(formName: string, initialValues: object): Action

setFieldErrors

setFieldErrors(formName: string, fieldName: string, errors: string[] | null): Action

Sets the field validation errors

setFieldStatus

setFieldStatus(formName: string, fieldName: string, status: EEasyFormFieldStatus): Action

Sets the field status

setFieldValue

setFieldValue(formName: string, fieldName: string, value: any): Action

Sets the value into the form field

setFormErrors

setFormErrors(formName: string, errors: string[] | null): Action

Sets the form errors

dropForm

dropForm(formName: string): Action

Clears all values, keeps all initials, and sets all statuses to pristine

Selectors

getForms

Returns forms state branch

createGetForm

createGetForm(formName: string): Selector

Returns the form state by the form name

createGetCommonFormErrors

createGetCommonFormErrors(formName: string): Selector

Returns the form errors (only common errors, except fields errors)

createGetFormAllFieldsErrors

createGetFormAllFieldsErrors(formName: string): Selector

Returns the form fields errors (common form errors not included)

createGetFormErrors

createGetFormErrors(formName: string): Selector

Returns all of the form validation errors

createGetIsFormValid

createGetIsFormValid(formName: string): Selector

Returns a boolean flag, whether the form is valid

createGetFormValues

createGetFormValues(formName: string): Selector

Returns values state branch of the form

createGetFormInitialValues

createGetFormInitialValues(formState: string): Selector

Returns initials state branch of the form

createGetFormStatuses

createGetFormStatuses(formName: string): Selector

Returns statuses state branch of the form

createGetIsFormPristine

createGetIsFormPristine(formName: string): Selector

Returns a boolean flag, whether all of the form fields are in pristine status

createGetFormFieldValue

createGetFormFieldValue(formName: string, fieldName: string): Selector

Returns the form field value (from values state branch)

createGetFormFieldInitialValue

createGetFormFieldInitialValue(formName: string, fieldName: string): Selector

Returns the form field initial value (from initials state branch)

createGetFormFieldErrors

createGetFormFieldErrors(formName: string, fieldName: string): Selector

Returns the form field errors (from errors state branch)

createGetIsFormFieldValid

createGetIsFormFieldValid(formName: string, fieldName: string): Selector

Returns a boolean flag of the validation result of the form field

createGetFormFieldStatus

createGetFormFieldStatus(formName: string, fieldName: string): Selector

Returns the form field status (from statuses state branch)

createGetIsFormFieldPristine

createGetIsFormFieldPristine(formName: string, fieldName: string): Selector

Returns a boolean flag, whether the form field is pristine

createGetFormFieldSafetyValue

createGetFormFieldSafetyValue(formName: string, fieldName: string): Selector

Returns a calculated current value of the form field. The Calculation includes the set value, the initial value and the field status.

createGetFormSafetyValues

createGetFormSafetyValues(formName: string): Selector

An analogue of createGetFormFieldSafetyValue selector-creator, but returns all of the values of the form