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

effector-rhf-adapter

v0.9.1

Published

**effector-rhf-adapter** — это библиотека, которая интегрирует [React Hook Form](https://react-hook-form.com/) с [Effector](https://effector.dev/) для управления формами в приложениях React. Он позволяет отслеживать изменения полей формы, ошибки, состояни

Downloads

196

Readme

effector-rhf-adapter

effector-rhf-adapter — это библиотека, которая интегрирует React Hook Form с Effector для управления формами в приложениях React. Он позволяет отслеживать изменения полей формы, ошибки, состояние формы и обрабатывать отправку данных с использованием возможностей реактивного управления состоянием Effector. С помощью этой библиотеки вы можете легко подписываться на изменения, контролировать ошибки и обновлять значения полей на основе событий Effector.

Installation

yarn add effector-rhf-adapter

API

index.tsx (cвязка формы React-hook-form и Effector)

import { FormProvider, useForm } from "react-hook-form";
import { useEffectorForm } from "effector-rhf-adapter";
import { createDeliveryEffectorForm } from "../../model/store";
import { FormType } from "../../model/form";

export const CreateDeliveryForm = () => {
    const form = useForm<CreateDeliveryFormType>();
    const { onSubmit } = useEffectorForm({
        form,
        effectorForm: createDeliveryEffectorForm,
    });

    return (
        <>
            <FormProvider {...form}>
                <form onSubmit={onSubmit}>
                {/*  fields...  */}
                </form>
            </FormProvider>
        </>
    );
};

store.ts

import { createEffect, createStore, sample } from "effector";
import { createEffectorForm } from "effector-rhf-adapter";
import { CreateDeliveryFormType } from "../../form";

const createDeliveryEffectorForm = createEffectorForm<CreateDeliveryFormType>();

const exampleFx = createEffect((params) => {
    console.log("Field changed params:", params);
});
const setContainerWeightEv = createEvent<string>();
const setContainersWeightEv = createEvent<string[]>();

// Пример подписки на изменение полей
sample({
    clock: createDeliveryEffectorForm.onWatchFieldsChanges([
        "containers.[].cargos.[].weight",
        "containers.[].cargos.cost",
    ]),
    target: exampleFx,
});

// Пример подписки на ошибки полей
sample({
    clock: createDeliveryEffectorForm.onWatchFieldsErrors([
        "containers.[].cargos.[].weight",
        "containers.[].cargos.cost",
    ]),
    target: exampleFx,
});

// Пример подписки на submit
sample({
    clock: createDeliveryEffectorForm.onFormSubmitEv(),
    target: exampleFx,
});

// Пример отслеживания изменения formState
sample({
    clock: createDeliveryEffectorForm.$formState,
    filter: (formState) => Boolean(formState),
    target: exampleFx,
});

// Пример изменения значения поля формы по событию
sample({
    clock: setContainerWeightEv,
    fn: (value) => ({ name: "container.0.weight", value }),
    target: createDeliveryEffectorForm.setValueEv,
});

// Пример изменения значений полей формы по событию
sample({
    clock: setContainersWeightEv,
    fn: (containersWeight) => ({
        fields: containersWeight.map((weight, index) => ({
            name: `container.${index}.weight`,
            value: weight,
        })),
    }),
    target: testForm.setValuesEv,
});

export { createDeliveryEffectorForm };

Методы отслеживания ошибок и изменений значения полей формы принимают один параметр - это массив строк, где каждый элемент массива это название отслеживаемого поля ввиде шаблона.

Измененное поле сопоставляется с массивом шаблонов и проверяется на соответствие методом isFieldChanged

Примеры работы шаблонов:

isFieldChanged(["field"], "field"); // true
isFieldChanged(["field"], "field.1.name"); // true
isFieldChanged(["field.1"], "field.2.name"); // false
isFieldChanged(["field.1.name"], "field.2.name"); // false
isFieldChanged(["field.2.name"], "field.2.name"); // true
isFieldChanged(["field.[].name"], "field.2.email"); // false
isFieldChanged(["field.[].subfields.[]"], "field.1.subfields.2.name"); // true
isFieldChanged(["field.1.subfields.1"], "field.1.subfields.2.name"); // false
isFieldChanged(["field.1.subfields.1"], "field.1.subfields.1.name"); // true
isFieldChanged(["field.[].subfields.[].name"], "field.1.subfields.2.name"); // true
isFieldChanged(["field.[].subfields.[].email"], "field.1.subfields.2.name"); // false

License

MIT