diff --git a/src/core/QueryManager.ts b/src/core/QueryManager.ts index 0d30f228c64..76dbdcff4c6 100644 --- a/src/core/QueryManager.ts +++ b/src/core/QueryManager.ts @@ -877,14 +877,16 @@ export class QueryManager { private getExtraReducers(): ApolloReducer[] { return Object.keys(this.observableQueries).map( obsQueryId => { - const queryOptions = this.observableQueries[obsQueryId].observableQuery.options; + const query = this.observableQueries[obsQueryId].observableQuery; + const queryOptions = query.options; + if (queryOptions.reducer) { return createStoreReducer( queryOptions.reducer, queryOptions.query, - queryOptions.variables || {}, + query.variables || {}, this.reducerConfig, - ); + ); } return null as never; }).filter( reducer => reducer !== null ); diff --git a/test/ObservableQuery.ts b/test/ObservableQuery.ts index d37e3b1e710..7f6689f7fe8 100644 --- a/test/ObservableQuery.ts +++ b/test/ObservableQuery.ts @@ -782,6 +782,66 @@ describe('ObservableQuery', () => { } }); }); + + it('applies query reducers with correct variables', (done) => { + const queryManager = mockQueryManager({ + // First we make the query + request: { query, variables }, + result: { data: dataOne }, + }, { + // Then we make a mutation + request: { query: mutation }, + result: { data: mutationData }, + }, { + // Then we make another query + request: { query, variables: differentVariables }, + result: { data: dataTwo }, + }, { + // Then we make another mutation + request: { query: mutation }, + result: { data: mutationData }, + }); + + + let lastReducerVars: Array = []; + let lastReducerData: Array = []; + const observable = queryManager.watchQuery({ + query, + variables, + reducer: (previous, action, reducerVars) => { + if (action.type === 'APOLLO_MUTATION_RESULT') { + // We want to track the history of the `variables` the reducer + // is given for the query. + lastReducerData.push(previous); + lastReducerVars.push(reducerVars); + } + + return previous; + } + }); + + // Check that the variables fed into the reducer are correct. + function assertVariables() { + assert.lengthOf(lastReducerVars, 2); + assert.deepEqual(lastReducerVars[0], variables); + assert.deepEqual(lastReducerData[0], dataOne); + assert.deepEqual(lastReducerVars[1], differentVariables); + assert.deepEqual(lastReducerData[1], dataTwo); + done(); + } + + // Subscribe to the query, then run the mutation, then change the variables, then run another mutation. + let sub = observable.subscribe({}); + queryManager.mutate({ mutation }).then(() => { + observable.setVariables(differentVariables); + queryManager.mutate({ mutation }).then(() => { + // We have to get out of the Promise scope here + // because the promises are capturing the assertion errors + // leading to timesouts. + setTimeout(assertVariables, 0); + }); + }); + }); }); }); });