gpt4 book ai didi

reactjs - Graphql - Apollo Client/React - 缓存 - fetchMore 不更新查询的数据状态

转载 作者:行者123 更新时间:2023-12-05 08:03:27 27 4
gpt4 key购买 nike

我尝试在我的 React 应用程序中使用 apollo 客户端实现缓存分页。

我的查询有过滤器参数,它应该是在缓存对象中创建新键的唯一参数。

出于某种原因,当 fetchMore 发生时指定了过滤器,新数据不会导致组件中的重新呈现。

我在合并函数中记录了现有的和传入的参数,似乎对于每个具有过滤器的 fetchMore,新数据确实到达了。所以,我不明白为什么组件没有重新渲染。

让事情变得更糟:使用或不使用过滤器多次调用 fetchMore 发送 http 请求并将传入数据与现有数据合并。我希望这不会发生,因为客户端应该看到它已经在缓存中有一个键,用于使用该键参数的查询。

查询如下:

query Shells($first: Int = 5, $offset: Int = 0, $filter: ShellFilter) {
shells(
orderBy: [STATUS_ASC, EXECUTION_FROM_DESC]
first: $first
offset: $offset
filter: $filter
) {
nodes {
...ShellData
}
totalCount
}
}

apolloClient 配置是这样的:

const client = new ApolloClient({
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
shells: {
keyArgs: ['filter'],
merge: (existing, incoming) => {
console.log('existing:', existing, 'incoming:', incoming);
return mergeObjectsAndNestedArrays<ShellsConnection>(
existing,
incoming,
'nodes',
);
},
},
},
},
},
})

以及显示它的组件:

const ControlCenter = () => {
const { showModal } = useModalContext();
const [page, setPage] = useState(1);
const { data, loading, fetchMore } = useShellsQuery();
const [query, setQuery] = useURLQuery();

const onCounterpartiesChange = async (counterparties) => {
await fetchMore({
variables: {
filter: { shellCounterParties: { some: { orgId: { in: '20584' } } } },
},
});
setQuery({ counterparties });
};

const shells = data?.shells?.nodes;

console.log('hello from shells:', shells);

这些是日志:

enter image description here

编辑 1 - 文档引用

遵循文档:https://www.apollographql.com/docs/react/pagination/key-args/#setting-keyargs

任何参数都可以用作 keyArgs:limitoffsetfilter

最佳答案

在文档示例中,用作键的 arg 是原始值,但在您的情况下,过滤器 arg 是一个对象。这可能会导致 apollo 将所有结果视为相同的缓存版本。如果您的数据仅取决于 orgID,我认为您可以尝试 nested array将该字段设置为键的符号。

keyArgs: ["filter", ["shellCounterParties", ["some", ["orgId", ["in"]]]]]

custom function

keyArgs: (args, context) => args.filter.shellCounterParties.some.orgId.in

如果你真的需要根据整个过滤器对象进行缓存,我想最简单的方法就是将它字符串化

keyArgs: (args, context) => JSON.stringify(args.filter)

但要确定 apollo 是如何缓存数据的,我强烈建议您尝试 apollo devtools

相关:https://github.com/apollographql/apollo-client/issues/7314

关于reactjs - Graphql - Apollo Client/React - 缓存 - fetchMore 不更新查询的数据状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73266671/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com