Mirror: The highly customizable and versatile GraphQL client with which you add on features like normalized caching as you grow.
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

feat: add minimumTime to refocusExchange to throttle query reexecution. (#3825)

authored by

Cas_ and committed by
GitHub
1d0ce5c1 d845f88b

+29 -6
+5
.changeset/old-cups-shake.md
··· 1 + --- 2 + '@urql/exchange-refocus': minor 3 + --- 4 + 5 + Add `minimumTime` to `refocusExchange` to throttle query reexecution.
+4 -1
exchanges/refocus/README.md
··· 22 22 23 23 const client = createClient({ 24 24 url: 'http://localhost:3000/graphql', 25 - exchanges: [refocusExchange(), cacheExchange, fetchExchange], 25 + exchanges: [refocusExchange({ 26 + // The minimum time in milliseconds to wait before another refocus can trigger. Default value is 0. 27 + minimumTime: 2000 28 + }), cacheExchange, fetchExchange], 26 29 }); 27 30 ```
+20 -5
exchanges/refocus/src/refocusExchange.ts
··· 1 1 import { pipe, tap } from 'wonka'; 2 2 import type { Exchange, Operation } from '@urql/core'; 3 3 4 + export interface RefocusOptions { 5 + /** The minimum time in milliseconds to wait before another refocus can trigger. 6 + * @defaultValue `0` 7 + */ 8 + minimumTime?: number; 9 + } 10 + 4 11 /** Exchange factory that reexecutes operations after a user returns to the tab. 5 12 * 13 + * @param opts - A {@link RefocusOptions} configuration object. 14 + * 6 15 * @returns a new refocus {@link Exchange}. 7 16 * 8 17 * @remarks ··· 14 23 * The `cache-and-network` policy will refetch data in the background, but will 15 24 * only refetch queries that are currently active. 16 25 */ 17 - export const refocusExchange = (): Exchange => { 26 + export const refocusExchange = (opts: RefocusOptions = {}): Exchange => { 27 + const { minimumTime = 0 } = opts; 28 + 18 29 return ({ client, forward }) => 19 30 ops$ => { 20 31 if (typeof window === 'undefined') { ··· 24 35 const watchedOperations = new Map<number, Operation>(); 25 36 const observedOperations = new Map<number, number>(); 26 37 38 + let lastHidden = 0; 39 + 27 40 window.addEventListener('visibilitychange', () => { 28 - if ( 29 - typeof document !== 'object' || 30 - document.visibilityState === 'visible' 31 - ) { 41 + const state = 42 + typeof document !== 'object' ? 'visible' : document.visibilityState; 43 + if (state === 'visible') { 44 + if (Date.now() - lastHidden < minimumTime) return; 32 45 watchedOperations.forEach(op => { 33 46 client.reexecuteOperation( 34 47 client.createRequestOperation('query', op, { ··· 37 50 }) 38 51 ); 39 52 }); 53 + } else { 54 + lastHidden = Date.now(); 40 55 } 41 56 }); 42 57