Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 630
Crazybud Avatar asked Apr 12 '18 13:04

Crazybud


People also ask

How do you update Apollo cache after mutation?

If a mutation updates a single existing entity, Apollo Client can automatically update that entity's value in its cache when the mutation returns. To do so, the mutation must return the id of the modified entity, along with the values of the fields that were modified.

How is mutation used in Apollo?

The useMutation React hook is the primary API for executing mutations in an Apollo application. As shown above, you use the gql function to parse the mutation string into a GraphQL document that you then pass to useMutation . Unlike useQuery , useMutation doesn't execute its operation automatically on render.

Does useMutation return a promise?

A function that performs an asynchronous task and returns a promise.


1 Answers

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.

like image 120
Kamil Kisiela Avatar answered Oct 12 '22 14:10

Kamil Kisiela