Skip to content

Commit

Permalink
fix: use hydrateAtoms for listField (#77)
Browse files Browse the repository at this point in the history
  • Loading branch information
MiroslavPetrik committed Jan 14, 2024
1 parent 8e12542 commit 9264c90
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export * from "./use-date-field-props";
export * from "./use-field-error";
export * from "./use-field-props";
export * from "./use-files-field-props";
export * from "./use-hydrate-field";
export * from "./use-list-actions";
export * from "./use-list-field";
export * from "./use-multiselect-field-props";
Expand Down
1 change: 1 addition & 0 deletions src/hooks/use-hydrate-field/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./useHydrateField";
20 changes: 20 additions & 0 deletions src/hooks/use-hydrate-field/useHydrateField.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { FieldAtom, RESET, UseAtomOptions } from "form-atoms";
import { useAtomValue } from "jotai";
import { useHydrateAtoms } from "jotai/utils";

export const useHydrateField = <Value>(
fieldAtom: FieldAtom<Value>,
initialValue?: Value | typeof RESET,
options?: UseAtomOptions,
) => {
const field = useAtomValue(fieldAtom);
useHydrateAtoms(
initialValue
? [
[field.value, initialValue],
[field._initialValue, initialValue],
]
: [],
options,
);
};
5 changes: 3 additions & 2 deletions src/hooks/use-list-field/useListField.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { UseFieldOptions, useFieldInitialValue } from "form-atoms";
import { UseFieldOptions } from "form-atoms";
import { useAtomValue } from "jotai";

import { ListAtomItems, ListAtomValue } from "../../atoms/list-atom";
import { ListField } from "../../fields";
import { useHydrateField } from "../use-hydrate-field";
import { useListActions } from "../use-list-actions";

export const useListField = <
Expand All @@ -12,13 +13,13 @@ export const useListField = <
list: ListField<Fields, Value>,
options?: UseFieldOptions<Value[]>,
) => {
useHydrateField(list, options?.initialValue, options);
const atoms = useAtomValue(list);
const splitItems = useAtomValue(atoms._splitList);
const formList = useAtomValue(atoms._formList);
const formFields = useAtomValue(atoms._formFields);
const isEmpty = useAtomValue(atoms.empty);
const { add, move, remove } = useListActions(list);
useFieldInitialValue(list, options?.initialValue, options);

const items = splitItems.map((item, index) => ({
item,
Expand Down

0 comments on commit 9264c90

Please sign in to comment.