+3
-1
src/esav/atoms.ts
+3
-1
src/esav/atoms.ts
+26
-4
src/esav/hooks.ts
+26
-4
src/esav/hooks.ts
···
6
6
queryStateFamily,
7
7
websocketAtom,
8
8
websocketStatusAtom,
9
-
addLogEntryAtom
9
+
addLogEntryAtom,
10
+
queryCacheAtom
10
11
} from './atoms';
11
12
import type { EsavDocument, QueryDoc, SubscribeMessage, UnsubscribeMessage } from './types';
12
13
import { atomWithStorage } from 'jotai/utils';
···
34
35
const ws = useAtomValue(websocketAtom);
35
36
const addLog = useSetAtom(addLogEntryAtom);
36
37
const wsStatus = useAtomValue(websocketStatusAtom);
37
-
const queryState = useAtomValue(queryStateFamily(queryId));
38
+
//const queryState = useAtomValue(queryStateFamily(queryId));
39
+
const liveQueryState = useAtomValue(queryStateFamily(queryId));
40
+
const [cache, setCache] = useAtom(queryCacheAtom);
41
+
const cachedQueryState = cache[queryId];
42
+
const queryState = liveQueryState ?? cachedQueryState;
43
+
useEffect(() => {
44
+
// If we receive valid new data from the live query, update our cache.
45
+
if (liveQueryState?.result) {
46
+
setCache((prevCache) => {
47
+
// Avoid unnecessary updates if the data is identical
48
+
if (prevCache[queryId] === liveQueryState) {
49
+
return prevCache;
50
+
}
51
+
return {
52
+
...prevCache,
53
+
[queryId]: liveQueryState,
54
+
};
55
+
});
56
+
}
57
+
}, [liveQueryState, queryId, setCache]);
58
+
38
59
const allDocuments = useAtomValue(documentsAtom);
39
60
40
61
const { enabled = true } = options;
···
87
108
}
88
109
});
89
110
};
90
-
}, [queryId, stringifiedEsQuery, enabled, ws, wsStatus, setActiveSubscriptions]);
111
+
}, [queryId, stringifiedEsQuery, enabled, ws, wsStatus, setActiveSubscriptions, addLog]);
91
112
92
113
93
114
const hydratedData = useMemo(() => {
···
97
118
.filter(Boolean);
98
119
}, [queryState?.result, allDocuments]);
99
120
100
-
const isLoading = wsStatus !== 'open' || queryState === null;
121
+
//const isLoading = wsStatus !== 'open' || queryState === null;
122
+
const isLoading = !queryState;
101
123
102
124
return {
103
125
data: hydratedData,