@@ -2,11 +2,13 @@ import {
22 Updater ,
33 deepIncludes ,
44 functionalUpdate ,
5+ getBatchedUpdates ,
56 getQueryArgs ,
67 isDocumentVisible ,
7- isPlainObject ,
88 isOnline ,
9+ isPlainObject ,
910 isServer ,
11+ scheduleMicrotask ,
1012} from './utils'
1113import { getResolvedQueryConfig } from './config'
1214import { Query } from './query'
@@ -66,6 +68,8 @@ type QueryCacheListener = (
6668 query ?: Query < unknown , unknown >
6769) => void
6870
71+ type NotifyCallback = ( ) => void
72+
6973// CLASS
7074
7175export class QueryCache {
@@ -75,13 +79,44 @@ export class QueryCache {
7579 private globalListeners : QueryCacheListener [ ]
7680 private queries : QueryHashMap
7781 private queriesArray : Query < any , any > [ ]
82+ private notifyQueue : NotifyCallback [ ]
83+ private notifyTransactions : number
7884
7985 constructor ( config ?: QueryCacheConfig ) {
8086 this . config = config || { }
8187 this . globalListeners = [ ]
8288 this . queries = { }
8389 this . queriesArray = [ ]
8490 this . isFetching = 0
91+ this . notifyQueue = [ ]
92+ this . notifyTransactions = 0
93+ }
94+
95+ batchNotifications ( callback : ( ) => void ) : void {
96+ this . notifyTransactions ++
97+ callback ( )
98+ this . notifyTransactions --
99+ if ( ! this . notifyTransactions && this . notifyQueue . length ) {
100+ scheduleMicrotask ( ( ) => {
101+ const batchedUpdates = getBatchedUpdates ( )
102+ batchedUpdates ( ( ) => {
103+ this . notifyQueue . forEach ( notify => {
104+ notify ( )
105+ } )
106+ this . notifyQueue = [ ]
107+ } )
108+ } )
109+ }
110+ }
111+
112+ scheduleNotification ( notify : NotifyCallback ) : void {
113+ if ( this . notifyTransactions ) {
114+ this . notifyQueue . push ( notify )
115+ } else {
116+ scheduleMicrotask ( ( ) => {
117+ notify ( )
118+ } )
119+ }
85120 }
86121
87122 notifyGlobalListeners ( query ?: Query < any , any > ) {
@@ -91,7 +126,9 @@ export class QueryCache {
91126 )
92127
93128 this . globalListeners . forEach ( listener => {
94- listener ( this , query )
129+ this . scheduleNotification ( ( ) => {
130+ listener ( this , query )
131+ } )
95132 } )
96133 }
97134
@@ -363,8 +400,10 @@ export function makeQueryCache(config?: QueryCacheConfig) {
363400export function onVisibilityOrOnlineChange ( type : 'focus' | 'online' ) {
364401 if ( isDocumentVisible ( ) && isOnline ( ) ) {
365402 queryCaches . forEach ( queryCache => {
366- queryCache . getQueries ( ) . forEach ( query => {
367- query . onInteraction ( type )
403+ queryCache . batchNotifications ( ( ) => {
404+ queryCache . getQueries ( ) . forEach ( query => {
405+ query . onInteraction ( type )
406+ } )
368407 } )
369408 } )
370409 }
0 commit comments