Shift 'n Tab
Shift 'n Tab

Reputation: 9443

How does Apollo-Client GraphQL refetchQueries works?

Any idea how do we get the response data from refetchQueries? I got the query response data from mutation.

Mutation

import { gql } from 'apollo-boost';

export const DONE_TASK = gql`
    mutation DoneTask($taskId: ID!) {
        doneTask(input: {
            taskId: $taskId
        }) {
            task {
                id
                status
            }
        }
    }
`;

Query

import { gql } from 'apollo-boost';

export const GET_TASKS_BY_STATUS = gql`
    query GetTasksByStatus($status: String!) {
        getTasksByStatus(status: $status) {
            edges {
                node {
                    id
                    status
                    description
                }
            }
        }
    }
`;

Usage

const response = await client.mutate({
    mutation: DONE_TASK,
    variables: {
        taskId: 1
    },
    refetchQueries: () => [{
        query: GET_TASKS_BY_STATUS,
        variables: { 
            status: "OPEN"
        },
    }]
});

console.log(response);
Output
data: {
    doneTask: {
        task: { id:  1, status: 'DONE'}
    }
}

But I expect a response data from GET_TASKS_BY_STATUS.

🤔 😕

Upvotes: 4

Views: 13467

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84677

Any queries you refetch through refetchQueries should already be used by some useQuery hook, Query component or graphql HOC. In order to access the data inside the same component as your mutation, you need to utilize the query being refetched inside that same component:

const { data } = useQuery(GET_TASKS_BY_STATUS, { variables: { status: 'OPEN' } })
const [mutate] = useMutation(DONE_TASK,{
  variables: {
    taskId: 1,
  },
  refetchQueries: () => [{
    query: GET_TASKS_BY_STATUS,
    variables: { 
      status: 'OPEN',
    },
  }],
})

Upvotes: 8

Related Questions