gpt4 book ai didi

graphql - 为什么我的 Apollo 缓存更新没有反射(reflect)在我的查询中?

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

我正在尝试使用 Apollo 缓存进行本地状态管理来存储表单的状态,这样它就可以在不清除的情况下返回。

我遇到了缓存正在更新但对缓存的后续查询返回陈旧数据的问题。我在使用 useQuery Hook 的 React 组件中遇到过这个问题,在 Apollo DevTools 中也遇到过这个问题,我将在下面用它来演示:

我在我的解析器中设置了这个突变和查询(我使用的是 Typescript):

const resolvers = {
Mutation: {
storeLetterDraft: (_root, args: { type: string, details: LetterSending }, { client, getCacheKey }) => {
const id = getCacheKey({
__typename: "LetterDraft",
id: args.type,
});

const data = { ...args.details };

client.writeFragment({
data,
id,
fragment: LETTER_SENDING_FRAGMENT,
});
},
},
Query: {
letterDraft: (_root, args: { type: string }, { client, getCacheKey }) => {
// I HAVE TRIED A DEBUGGER STATEMENT HERE
const id = getCacheKey({
__typename: "LetterDraft",
id: args.type,
});

return client.readFragment({
id,
fragment: LETTER_SENDING_FRAGMENT,
});
},
},
}

我的片段是:

export const LETTER_SENDING_FRAGMENT = gql`
fragment DraftLetterSending on LetterDraft {
date
firstName
lastName
addressLine1
addressLine2
addressTown
addressCounty
addressPostcode
}
`;

我正在初始化我的缓存:

cache.writeData({
data: {
letterDrafts: [{
__typename: "LetterDraft",
id: "CREATE",
addressCounty: "Northamptonshire",
addressLine1: "1 Watkin Terrace",
addressLine2: "",
addressPostcode: "NN1 3ER",
addressTown: "Northampton",
date: "2019-11-01",
firstName: "d",
lastName: "d",
}],
},
});

我的突变看起来像:

export const storeCreateLetterSendingMutation = gql`
mutation StoreCreateLetterSending($details: LetterSending!) {
storeLetterDraft(type: "CREATE", details: $details) @client
}
`;

突变之前,Apollo DevTools 中的缓存看起来符合预期:

Cache before mutation

查询按预期返回:

Query before mutation

执行突变后,缓存更新:

Cache after mutation

但是,再次运行查询会导致数据过时:

enter image description here

有趣的是,如果我在上面的部分中放置了一个调试器语句(我已经在此处尝试了一个 DEBUGGER STATEMENT),那么查询解析器似乎是第一次运行,而不是第二次,所以查询似乎正在被缓存 - 即使它是我正在更新的缓存!因此,我认为问题在于查询随后没有运行解析器。

最佳答案

我在文档中遗漏了这一点(Apollo 网站上有很多地方详细介绍了本地缓存和@client。

https://www.apollographql.com/docs/react/essentials/local-state/#forcing-resolvers-with-clientalways-true

While leveraging the cache for both local and remote results can be super helpful in a lot of cases, it's not always the best fit. We might want to use a local resolver to calculate a dynamic value that needs to be refreshed on every request, while at the same time continue to use the cache for the network based parts of our query. To support this use case, Apollo Client's @client directive accepts an always argument, that when set to true will ensure that the associated local resolver is run on every request.

关于graphql - 为什么我的 Apollo 缓存更新没有反射(reflect)在我的查询中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58039551/

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