Skip to content

useArrayField

Use array field model in react component

Type Signature:

ts
function useArrayField<
  T extends ArrayField<any>,
  Value extends ArrayFieldItemType = T extends ArrayField<any, any, infer D>
    ? D
    : never,
  Meta extends object = T extends ArrayField<any, infer D> ? D : any,
>(field: T): ReactArrayFieldApi<Value, Meta>;

Example Usage:

TIP

You can use useArrayField with field of form for optimization like this:

ts
const form = createForm({ schema: { friends: [] } });

// in react component
const { values, onChange } = useArrayField(form.fields.friends);
tsx
import { createArrayField, createField } from "@effector-reform/core";
import { useArrayField, useField } from "@effector-reform/react";
import { useCallback } from "react";

const newIncomeField = createField(0);
const incomesField = createArrayField<number>([]);

const Field = () => {
  const newIncome = useField(newIncomeField);
  const incomes = useArrayField(incomesField);

  const addIncome = useCallback(() => {
    incomes.push(newIncome.value);
    newIncome.reset();
  }, [newIncome.value, incomes.push]);

  return (
    <>
      <p>My budget</p>

      <div>
        {incomes.values.map(income => <span>${income}</span>)}
      </div>

      <p>add income</p>

      <input
        type="number"
        value={newIncome.value}
        onChange={(event) => newIncome.onChange(parseInt(event.currentTarget.value))}
      />

      <button onClick={addIncome}>
        add
      </button>
    </>
  )
}

API

nametypedescription
values(T extends ReadyFieldsGroupSchema ? ReactFields<T> : T)[]array field values
metaMetaarray field meta
errorFieldErrorarray field error
isValidbooleanis array field valid
onReset() => voidreset array field values
onChange(values: Payload[]) => voidchange array field values
onChangeError(error: FieldError) => voidchange array field outer error
onChangeMeta(meta: Meta) => voidchange field meta
onPush(payload: PushPayload<Payload>) => voidpush itemreference
onSwap(payload: SwapPayload) => voidswap itemsreference
onMove(payload: MovePayload) => voidmove itemreference
onInsert(payload: InsertOrReplacePayload<Payload>) => voidinsert itemreference
onUnshift(payload: UnshiftPayload<Payload>) => voidunshift item(s)reference
onRemove(payload: RemovePayload) => voidremove itemreference
onPop(payload: void) => voidpop itemreference
onReplace(payload: InsertOrReplacePayload<Payload>) => voidreplace itemreference

Released under the MIT License.