Skip to content

Commit

Permalink
add getOrInsert method to ListStore
Browse files Browse the repository at this point in the history
  • Loading branch information
George-Payne committed May 13, 2024
1 parent bf9af90 commit a643d2e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .changeset/beige-pans-try.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@eventstore-ui/stores': minor
---

Get's a single item from the list store, or inserts a default and returns it.

```ts
const item = store.getOrInsert('my-id', () => ({
id: 'my-id',
value: Math.random(),
}));
```
8 changes: 8 additions & 0 deletions packages/stores/src/stores/createListStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ export interface ListStore<T> {
) => Array<R>;
/** Get a single item from the list. */
get: (id: string) => T | undefined;
/** Get a single item from the list, or insert a default and return it */
getOrInsert: (id: string, defaultValue: () => T) => T;
/** Check if an item is available in the list. */
has: (id: string) => boolean;
/** Returns an array of all the keys in the store. */
Expand Down Expand Up @@ -99,6 +101,12 @@ export const createListStore = <T>(
return acc;
}, []),
get: (id) => state[id],
getOrInsert: (id, defaultValue) => {
if (!(id in state)) {
state[id] = defaultValue();
}
return state[id];
},
has: (id) => id in state,
keys: () => Object.keys(state),
onChange: (...args: any[]) => {
Expand Down

0 comments on commit a643d2e

Please sign in to comment.