Ad

How Does Apollo-Client GraphQL RefetchQueries Works?

- 1 answer

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.

🤔 😕

Ad

Answer

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',
    },
  }],
})
Ad
source: stackoverflow.com
Ad