Skip to content

Commit

Permalink
fix: reuse the buildItem method when adding items to the list
Browse files Browse the repository at this point in the history
  • Loading branch information
MiroslavPetrik committed Mar 5, 2024
1 parent dc0c06f commit b9e0af5
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 18 deletions.
14 changes: 4 additions & 10 deletions src/atoms/list-atom/listAtom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export type ListAtom<Fields extends FormFields, Value> = ExtendFieldAtom<
* @internal
*/
_formFields: Atom<Fields[]>;
buildItem(): ListItemForm<Fields>;
buildItem(fields?: Fields): ListItemForm<Fields>;
}
>;

Expand Down Expand Up @@ -102,22 +102,16 @@ export function listAtom<
}
}

function buildItem(): ListItemForm<Fields> {
function buildItem(fields?: Fields): ListItemForm<Fields> {
return listItemForm({
fields: formBuilder(),
fields: fields ?? formBuilder(),
getListNameAtom: (get) => get(self).name,
formListAtom: _formListAtom,
});
}

const makeFormList = (): ListItemForm<Fields>[] =>
formBuilder(config.value).map((fields) =>
listItemForm({
fields,
getListNameAtom: (get) => get(self).name,
formListAtom: _formListAtom,
}),
);
formBuilder(config.value).map(buildItem);

const initialFormListAtom = atomWithDefault(makeFormList);
const _formListAtom = atomWithDefault((get) => get(initialFormListAtom));
Expand Down
9 changes: 1 addition & 8 deletions src/hooks/use-list-actions/useListActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { useAtomValue, useSetAtom } from "jotai";
import { useCallback, useMemo, useTransition } from "react";

import { ListAtom, ListItem } from "../../atoms/list-atom";
import { listItemForm } from "../../atoms/list-atom/listItemForm";

export const useListActions = <Fields extends FormFields, Value>(
listAtom: ListAtom<Fields, Value>,
Expand All @@ -24,13 +23,7 @@ export const useListActions = <Fields extends FormFields, Value>(
const add = useCallback((before?: ListItem<Fields>, fields?: Fields) => {
dispatchSplitList({
type: "insert",
value: fields
? listItemForm({
fields,
getListNameAtom: (get) => get(listAtom).name,
formListAtom: atoms._formList,
})
: atoms.buildItem(),
value: atoms.buildItem(fields),
before,
});
startTransition(() => {
Expand Down

0 comments on commit b9e0af5

Please sign in to comment.