Skip to content

Commit

Permalink
Broadcast cache writes to all tabs/windows
Browse files Browse the repository at this point in the history
This allows fresh data from one tab to be applied to all tabs.
Each tab still has its own cache, changes are just synced.
So refreshing the page will still initialize empty, so if some data point
became stale (now in all tabs), the user can refresh one page,
and the fresh data will refresh all tabs.
  • Loading branch information
CarsonF committed Oct 14, 2024
1 parent 785560f commit 16d581f
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/api/client/createCache.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { InMemoryCache, PossibleTypesMap, TypePolicies } from '@apollo/client';
import { Cache } from '@apollo/client/cache';
import { possibleTypes } from '../schema/fragmentMatcher';
import { typePolicies } from '../schema/typePolicies';

Expand Down Expand Up @@ -26,5 +27,16 @@ export const createCache = () => {
}
}

if (typeof BroadcastChannel !== 'undefined') {
const writeChannel = new BroadcastChannel('apollo::write');
const orig = cache.write.bind(cache);
const ourWrite = (options: Cache.WriteOptions, sendToOthers = true) => {
sendToOthers && writeChannel.postMessage(options);
return orig(options);
};
writeChannel.onmessage = (event) => ourWrite(event.data, false);
cache.write = ourWrite;
}

return cache;
};

0 comments on commit 16d581f

Please sign in to comment.