Apollo 客户端 - 使用 useLazyQuery 获取更多,变量不更新(用于偏移分页)

问题描述 投票:0回答:2

预期结果: 我们按照 apollo 文档(https://www.apollographql.com/docs/react/pagination/offset-based/)进行了分页实现。使用读取/合并功能 一旦我们调用 fetchMore 函数并手动更新变量,我们期望使用新变量调用 read 函数。

Apollo docs snippet

实际结果: 我们无法使分页正常工作,数据已正确获取但未正确显示。显示不良是由于变量未更新造成的。 “读取”函数始终接收原始查询的变量。

useEffect(() => {
    if (isDefined(fetchMore)) {
      fetchMore({
        variables: {
          offset:
            currentPage === 1
              ? (currentPage - 1) * total
              : (currentPage - 1) * total + 1,
          first: total,
          searchString: searchString
        }
      })
    } else {
      getData({
        variables: {
          offset: 0,
          first: total,
          searchString: searchString
        }
      })
    }    }, [currentPage, fetchMore, searchString, getData])

我们还尝试手动更新变量,因为我们不使用 useQuery,而是使用 useLazyQuery。

 client
    .watchQuery({
      query: GET_REPORTS,
      variables: {
        offset: 0,
        first: total,
        searchString: searchString
      }
    })
    .setVariables({
      offset:
        currentPage === 1
          ? (currentPage - 1) * total
          : (currentPage - 1) * total + 1,
      first: 25,
      searchString
    })

我们的类型政策:

typePolicies: {
        Query: {
          fields: {
            REPORT: {
              keyArgs: false,
              read(existing, {args}) {
                **//here we would expect for our args to change, the moment we try fetch our 
                //second page**
                return existing && existing.slice(args.offset, args.offset + args.first)
              },
    
              // The keyArgs list and merge function are the same as above.
    
              merge(existing, incoming, { args: { offset = 0 } }) {
                const merged = existing ? existing.slice(0) : []
                for (let i = 0; i < incoming.length; ++i) {
                  merged[offset + i] = incoming[i]
                }
                return merged
              }
            }
          }
      }
    }
apollo-client react-apollo
2个回答
0
投票

使用

refetch
代替
fetchMore

示例:

const { data, loading, refetch } = useQuery(GET_USER_BANK_ACCOUNTS, {
        fetchPolicy: 'no-cache'
    })

-1
投票

我之前也遇到过同样的问题,事实证明,由于您使用的是 useLazyQuery,因此您必须先查询该函数,然后使用 fetchMore。

示例

const [getList,{loading, fetchMore}] = useLazyQuery (GET_LIST)
然后实现这样的条件;
if(! fetchMore){ getList(....passargs) }else{ fetchMore (...passargs) } 
这是因为如果不调用 getList,fetchMore 将是未定义的。

© www.soinside.com 2019 - 2024. All rights reserved.