首页 > 解决方案 > Apollo 客户端 useMutation 挂钩中的 refetchQueries 问题

问题描述

尝试refetchQueries在我的useMutation钩子中定义时遇到以下错误。

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

我不确定我做错了什么,因为官方的 Apollo 文档有点不清楚,我在谷歌搜索时找不到任何优先级。

据我了解该错误,query我的 GraphQL 查询中缺少该属性。我是否将正确的值传递给refetchQueries? 我认为我做得对,但后来我不知道为什么它抱怨query不参与其中。

代码

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'
      ]
    } )
  }
}

查询

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
            }
        }
    }
`;

标签: reactjsgraphqlapollo-clientreact-apollographql-mutation

解决方案


自己找到了答案。尽管它看起来不像文档中的任何内容,但以下内容有效:

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

我想它说该属性query丢失了,所以我只是尝试使用该query属性传递一个对象,认为它永远不会起作用,但它确实如此。


推荐阅读