当输入对象中的变量设置为未定义或空字符串时,useQuery 不会触发

CKA*_*CKA 3 apollo graphql react-apollo apollo-client

我有一个需要输入参数的查询,比如日期

  const { loading, data, error } = useQuery(GET_LIST, {
    variables: {
      input: {
        date: date,
      },
    },
  });

Run Code Online (Sandbox Code Playgroud)
export const GET_LIST = gql`
  query list($input: ListParams) {
    list(input: $input) {
      totalCount
      recordCount
      list {
        listId
        date
        qty
        amount
        currency
      }
    }
  }
`;
Run Code Online (Sandbox Code Playgroud)
input ListParams {
  date: String
}
Run Code Online (Sandbox Code Playgroud)

我需要获取列表,用户可以根据日期进行过滤。现在,在初始加载时,未设置日期,而是调用查询。用户设置日期,没有问题,使用日期值再次调用查询,现在当用户删除日期过滤器时,日期值变得未定义,我希望这次再次调用 useQuery ,没有变量,但它从未被调用过。

我也尝试过设置空字符串,即使这样 useQuery 也不会被调用,这不是预期的行为

 input: {
        date: date||'',
      },
Run Code Online (Sandbox Code Playgroud)

gaz*_*007 5

当您传递到 useQuery 挂钩的查询变量与先前的值相同时,Apollo-Cilent 具有缓存机制。

文档: https: //www.apollographql.com/docs/react/data/queries/ 沙箱: https: //codesandbox.io/embed/usequery-example-apollo-client3-dx626

您可以通过使用 useQuery 挂钩中内置的重新获取或轮询机制来解决此问题:

function Date({ date }) {

const { loading, data, error, refetch } = useQuery(GET_LIST, {
    variables: {
      input: {
        date: date,
      },
    },
  });
//...
return (<div>
      <Component data={data} onDateChange={() => refetch()}/>
    </div>)
}
Run Code Online (Sandbox Code Playgroud)

或者,如果查询中的空/未定义变量没有特定目的,您可能不应该通过在 useQuery 挂钩中添加变量来添加{!input.date && <Date /> }或不发送任何查询来呈现组件:skip


const { loading, data, error, refetch } = useQuery(GET_LIST, {
    variables: {
      input: {
        date: date,
      },
    },
    skip: !input?.date // <------ Skip the query when input.date is missing or empty
  });
Run Code Online (Sandbox Code Playgroud)

迟到的回答(我认为您可能已经解决了这个问题),我在这里写了一些注释,以防其他人遇到这个问题。