@@ -5,29 +5,49 @@ import { DataSubscription, DataSyncController } from './ihp-datasync.js';
5
5
// Therefore the default value is true.
6
6
export const AuthCompletedContext = React . createContext ( true ) ;
7
7
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
+
8
15
/**
9
16
* Returns the result of the current query in real-time. Returns `null` while the data is still being fetched from the server.
10
17
* @example
11
18
* const messages = useQuery(query('messages').orderBy('createdAt'));
12
19
*/
13
20
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
+ } ) ;
15
26
const isAuthCompleted = useContext ( AuthCompletedContext ) ;
16
27
17
28
useEffect ( ( ) => {
18
29
if ( ! isAuthCompleted ) {
19
30
return ;
20
31
}
32
+
33
+ const strinigifiedQuery = JSON . stringify ( queryBuilder . query ) ;
34
+ const cachedRecords = recordsCache . get ( strinigifiedQuery ) ;
21
35
22
36
// Invalidate existing records, as the query might have been changed
23
- setRecords ( null ) ;
37
+ setRecords ( cachedRecords === undefined ? null : cachedRecords ) ;
24
38
25
39
const dataSubscription = new DataSubscription ( queryBuilder . query ) ;
26
40
dataSubscription . createOnServer ( ) ;
27
41
28
42
// The dataSubscription is automatically closed when the last subscriber on
29
43
// 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
+ } ) ;
31
51
} , [
32
52
JSON . stringify ( queryBuilder . query ) /* <-- It's terrible - but it works, we should find a better for this */ ,
33
53
isAuthCompleted
0 commit comments