Skip to content

Commit 838322a

Browse files
authored
Merge pull request krausest#4 from dai-shi/jotai-v1-atoms-in-atom
fix to follow keyed category
2 parents a57acea + 7d9610a commit 838322a

File tree

2 files changed

+9
-28
lines changed

2 files changed

+9
-28
lines changed

frameworks/keyed/jotai/src/main.tsx

+4-19
Original file line numberDiff line numberDiff line change
@@ -3,26 +3,13 @@ import ReactDOM from "react-dom";
33
import { atom, useAtom, PrimitiveAtom } from "jotai";
44
import { useUpdateAtom } from "jotai/utils";
55

6-
import { Data, buildNextItem, buildDataAtoms } from "./utils";
6+
import { Data, buildDataAtoms } from "./utils";
77

88
const dataAtom = atom<PrimitiveAtom<Data>[]>([]);
99
const selectedAtom = atom<PrimitiveAtom<Data> | null>(null);
1010

11-
const createRowsAtom = atom(null, (get, set, amount: number) => {
12-
const prevData = get(dataAtom);
13-
const data = new Array(amount);
14-
for (let i = 0; i < amount; i++) {
15-
const prev = prevData[i]
16-
if (prev) {
17-
data[i] = prev;
18-
set(prev, buildNextItem());
19-
} else {
20-
data[i] = atom(buildNextItem());
21-
}
22-
}
23-
if (prevData.length !== data.length) {
24-
set(dataAtom, data);
25-
}
11+
const createRowsAtom = atom(null, (_, set, amount: number) => {
12+
set(dataAtom, buildDataAtoms(amount));
2613
set(selectedAtom, null);
2714
});
2815

@@ -57,9 +44,7 @@ const clearStateAtom = atom(null, (_, set) => {
5744
const swapRowsAtom = atom(null, (get, set) => {
5845
const data = get(dataAtom);
5946
if (data.length > 998) {
60-
const tmp = get(data[1]);
61-
set(data[1], get(data[998]));
62-
set(data[998], tmp);
47+
set(dataAtom, [data[0], data[998], ...data.slice(2, 998), data[1], data[999]])
6348
}
6449
});
6550

frameworks/keyed/jotai/src/utils.ts

+5-9
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,15 @@ export interface Data {
1515
label: string;
1616
}
1717

18-
export function buildNextItem(): Data {
19-
return {
18+
export function buildDataAtoms(count: number): PrimitiveAtom<Data>[] {
19+
const data = new Array(count);
20+
for (let i = 0; i < count; i++) {
21+
data[i] = atom({
2022
id: nextId++,
2123
label: `${A[random(A.length)]} ${C[random(C.length)]} ${
2224
N[random(N.length)]
2325
}`,
24-
};
25-
}
26-
27-
export function buildDataAtoms(count: number): PrimitiveAtom<Data>[] {
28-
const data = new Array(count);
29-
for (let i = 0; i < count; i++) {
30-
data[i] = atom(buildNextItem());
26+
});
3127
}
3228
return data;
3329
}

0 commit comments

Comments
 (0)