Issue with refetchQueries in the Apollo Client useMutation hook
Asked Answered
G

1

7

I'm running into the following error while trying to define refetchQueries in my useMutation hook.

Type 'DocumentNode' is not assignable to type 'string | PureQueryOptions'.  
Property 'query' is missing in type 'DocumentNode' but required in type 'PureQueryOptions'.

I'm not sure what I'm doing wrong as the official Apollo documentation is a bit unclear on it and I can't find any precedence when Googling.

As I understand the error, the property query is missing from my GraphQL query. Am I passing the right value to the refetchQueries? I think I'm doing it correctly, but then I don't know why it's complaining about query not being part of it.

Code

import { useMutation, useQuery } from '@apollo/client';
import { GET_CUSTOMERS, MARK_AS_VIP } from './queries';

export default function Customers() {
  const [ markAsVIP, { data: vips, loading: vipLoading, error: vipError } ] = useMutation( MARK_AS_VIP );
  const { loading, error, data: getCustomerResp } = useQuery( GET_CUSTOMERS );

  const handleMarkAsVIP = ( customerId: string ) => {
    markAsVIP( {
      variables: { id: customerId, tags: [ 'VIP' ] },
      refetchQueries: [
        GET_CUSTOMERS, // error shows here
        'getCustomers'
      ]
    } )
  }
}

Queries

import { gql } from '@apollo/client';

export const GET_CUSTOMERS = gql`
  query getCustomers {
      customers( first: 50 ) {
          edges {
              cursor
              node {
                  id
                  displayName
                  tags
              }
          }
      }
  }
  `;

export const MARK_AS_VIP = gql`
    mutation markAsVIP( $id: ID!, $tags: [String!]! ) {
        tagsAdd( id: $id, tags: $tags ) {
            node {
                id
            }
            userErrors {
                field
                message
            }
        }
    }
`;
Greg answered 31/7, 2021 at 10:48 Comment(0)
G
17

Found the answer myself. Although it doesn't look like anything in the docs, the following worked:

const handleMarkAsVIP = ( customerId: string ) => {
  markAsVIP({
    variables: { id: customerId, tags: [ 'VIP' ] },
    refetchQueries: [
       { query: GET_CUSTOMERS },
      'getCustomers'
    ]
  })
}

I figured it said the property query was missing, so I simply tried passing an object with the query property, thinking it would never work, but it does.

Greg answered 31/7, 2021 at 11:45 Comment(3)
Thanks! I had exactly the same issue, but couldn't figure it out :DEpirogeny
There is an issue that your GET_CUSTOMERS query will work without most recently provided set of variables.Underwriter
Thanks... I am surprised not to see this in the official docs.Flashboard

© 2022 - 2024 — McMap. All rights reserved.