forked from lencx/ChatGPT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useData.ts
70 lines (60 loc) · 1.52 KB
/
useData.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { useState, useEffect } from 'react';
import { v4 } from 'uuid';
export const safeKey = Symbol('chat-id');
export default function useData(oData: any[]) {
const [opData, setData] = useState<any[]>([]);
useEffect(() => {
opInit(oData);
}, []);
const opAdd = (val: any) => {
const v = [val, ...opData];
setData(v);
return v;
};
const opInit = (val: any[] = []) => {
if (!val || !Array.isArray(val)) return;
const nData = val.map((i) => ({ [safeKey]: v4(), ...i }));
setData(nData);
};
const opRemove = (id: string) => {
const nData = opData.filter((i) => i[safeKey] !== id);
setData(nData);
return nData;
};
const opRemoveItems = (ids: string[]) => {
const nData = opData.filter((i) => !ids.includes(i[safeKey]));
setData(nData);
return nData;
};
const opReplace = (id: string, data: any) => {
const nData = [...opData];
const idx = opData.findIndex((v) => v[safeKey] === id);
nData[idx] = data;
setData(nData);
return nData;
};
const opReplaceItems = (ids: string[], data: any) => {
const nData = [...opData];
let count = 0;
for (let i = 0; i < nData.length; i++) {
const v = nData[i];
if (ids.includes(v[safeKey])) {
count++;
nData[i] = { ...v, ...data };
}
if (count === ids.length) break;
}
setData(nData);
return nData;
};
return {
opSafeKey: safeKey,
opInit,
opReplace,
opAdd,
opRemove,
opRemoveItems,
opData,
opReplaceItems,
};
}