angulargraphqlapollo

Angular Apollo use response from refetch query within a mutation


I'm working on an Angular project with Apollo and GraphQL. I have a mutation that updates a list of accounts with relevant details associated with it. After the successful mutation, I am using refetchqueries to query the API for updated list of accounts. Everything works till this part.

this.apollo.mutate({
        mutation: mutationCreateNewAccount,
        variables: {
            accountNumber: this.accountNumber,
            accountType: this.accountType,
            routingNumber: this.routingNumber,
            nameOfAcountHolder: this.name
        },
        refetchQueries: [{
            query: queryAccounts,
            variables: { accountNumber: this.accountNumber }
        }]}).subscribe(({ data }) => console.log(data),

The 'data' for the subscription returns response from the mutation but is there a way I could use the data returned by 'queryAccounts' which is also run as part of this mutation?

There seems to be a way to do this in react but I was unsuccessful to do something similar in Angular.


Solution

  • You mentioned there are ways to do it in react and which I don't think is true.

    Let me explain how mutations work in Apollo.

    1. You run apollo.mutate() with refetchQueries option
    2. When you subscribe to it, the HTTP request is made (in most cases, sometimes WS or some other transportation layer)
    3. Apollo receives the response from the server.
    4. Updates the store.
    5. Observable you subscribed to emits the result (your console.log(data))
    6. Next, each query specified in refetchQueries starts a new HTTP request and runs against the server.
    7. Apollo updates the store on each response.
    8. Components that listen to those queries get updated results

    I explained it here, in docs: https://www.apollographql.com/docs/angular/features/cache-updates.html#after-mutations

    Basically, refetchQueries is not to fetch or access data.