Skip to content

Commit

Permalink
Remove optimistic layer at same time as final mutation update.
Browse files Browse the repository at this point in the history
  • Loading branch information
benjamn committed Apr 16, 2021
1 parent 28e9dc3 commit d9e39f5
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/cache/core/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ export type BatchOptions<C extends ApolloCache<any>> = {
// the same as passing null.
optimistic: string | boolean;

removeOptimistic?: string;

// If you want to find out which watched queries were invalidated during
// this batch operation, pass this optional callback function. Returning
// false from the callback will prevent broadcasting this result.
Expand Down
5 changes: 5 additions & 0 deletions src/cache/inmemory/inMemoryCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,7 @@ export class InMemoryCache extends ApolloCache<NormalizedCacheObject> {
const {
transaction,
optimistic = true,
removeOptimistic,
} = options;

const perform = (layer?: EntityStore) => {
Expand Down Expand Up @@ -363,6 +364,10 @@ export class InMemoryCache extends ApolloCache<NormalizedCacheObject> {
perform();
}

if (typeof removeOptimistic === "string") {
this.optimisticData = this.optimisticData.removeLayer(removeOptimistic);
}

// Note: if this.txCount > 0, then alreadyDirty.size === 0, so this code
// takes the else branch and calls this.broadcastWatches(options), which
// does nothing when this.txCount > 0.
Expand Down
7 changes: 7 additions & 0 deletions src/core/QueryManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ export class QueryManager<TStore> {
result,
document: mutation,
variables,
removeOptimistic: !!optimisticResponse,
errorPolicy,
context,
updateQueries,
Expand Down Expand Up @@ -311,6 +312,7 @@ export class QueryManager<TStore> {
context?: TContext;
updateQueries: UpdateQueries<TData>;
update?: MutationUpdaterFunction<TData, TVariables, TContext, TCache>;
removeOptimistic: boolean;
onQueryUpdated?: OnQueryUpdated;
},
cache = this.cache,
Expand Down Expand Up @@ -382,6 +384,10 @@ export class QueryManager<TStore> {
// Write the final mutation.result to the root layer of the cache.
optimistic: false,

removeOptimistic: mutation.removeOptimistic
? mutation.mutationId
: void 0,

onWatchUpdated: mutation.onQueryUpdated && ((watch, diff) => {
if (watch.watcher instanceof QueryInfo) {
const oq = watch.watcher.observableQuery;
Expand Down Expand Up @@ -420,6 +426,7 @@ export class QueryManager<TStore> {
try {
this.markMutationResult<TData, TVariables, TContext, TCache>({
...mutation,
removeOptimistic: false,
result: { data },
}, cache);
} catch (error) {
Expand Down

0 comments on commit d9e39f5

Please sign in to comment.