Skip to content

Commit 70ec375

Browse files
committed
Added caching to DataSync
Fixes digitallyinduced/thin-backend#31
1 parent e2e350b commit 70ec375

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

lib/IHP/DataSync/react.js

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,29 +5,49 @@ import { DataSubscription, DataSyncController } from './ihp-datasync.js';
55
// Therefore the default value is true.
66
export const AuthCompletedContext = React.createContext(true);
77

8+
// To avoid too many loading spinners when going backwards and forwards
9+
// between pages, we cache the result of queries so we can already showing
10+
// some data directly after a page transition. The data might be a bit
11+
// outdated, but it will directly be overriden with the latest server state
12+
// once it has arrived.
13+
const recordsCache = new Map();
14+
815
/**
916
* Returns the result of the current query in real-time. Returns `null` while the data is still being fetched from the server.
1017
* @example
1118
* const messages = useQuery(query('messages').orderBy('createdAt'));
1219
*/
1320
export function useQuery(queryBuilder) {
14-
const [records, setRecords] = useState(null);
21+
const [records, setRecords] = useState(() => {
22+
const strinigifiedQuery = JSON.stringify(queryBuilder.query);
23+
const cachedRecords = recordsCache.get(strinigifiedQuery);
24+
return cachedRecords === undefined ? null : cachedRecords;
25+
});
1526
const isAuthCompleted = useContext(AuthCompletedContext);
1627

1728
useEffect(() => {
1829
if (!isAuthCompleted) {
1930
return;
2031
}
32+
33+
const strinigifiedQuery = JSON.stringify(queryBuilder.query);
34+
const cachedRecords = recordsCache.get(strinigifiedQuery);
2135

2236
// Invalidate existing records, as the query might have been changed
23-
setRecords(null);
37+
setRecords(cachedRecords === undefined ? null : cachedRecords);
2438

2539
const dataSubscription = new DataSubscription(queryBuilder.query);
2640
dataSubscription.createOnServer();
2741

2842
// The dataSubscription is automatically closed when the last subscriber on
2943
// the DataSubscription object has been unsubscribed
30-
return dataSubscription.subscribe(setRecords);
44+
45+
return dataSubscription.subscribe(records => {
46+
setRecords(records);
47+
48+
// Update the cache whenever the records change
49+
recordsCache.set(strinigifiedQuery, records);
50+
});
3151
}, [
3252
JSON.stringify(queryBuilder.query) /* <-- It's terrible - but it works, we should find a better for this */,
3353
isAuthCompleted

0 commit comments

Comments
 (0)