Files
cinny/src/app/state/list.ts
T

34 lines
818 B
TypeScript
Raw Normal View History

2023-06-12 21:15:23 +10:00
import { atom } from 'jotai';
export type ListAction<T> =
| {
type: 'PUT';
item: T | T[];
}
| {
type: 'DELETE';
item: T | T[];
};
export const createListAtom = <T>() => {
const baseListAtom = atom<T[]>([]);
2024-01-21 23:50:56 +11:00
return atom<T[], [ListAction<T>], undefined>(
2023-06-12 21:15:23 +10:00
(get) => get(baseListAtom),
(get, set, action) => {
const items = get(baseListAtom);
const newItems = Array.isArray(action.item) ? action.item : [action.item];
if (action.type === 'DELETE') {
set(
baseListAtom,
items.filter((item) => !newItems.includes(item))
);
return;
}
if (action.type === 'PUT') {
set(baseListAtom, [...items, ...newItems]);
}
}
);
};
export type TListAtom<T> = ReturnType<typeof createListAtom<T>>;