【发布时间】:2021-03-24 03:06:54
【问题描述】:
首先,感谢您花时间阅读本文。
我尝试在基于几种方法的突变后更新缓存。
起初,我在考虑使用上下文,但是当我阅读文档时,我意识到这种方法对于 Apollo 来说是不必要的,因为状态存储在缓存中。
我一直在探索这些文件: Making all other cache updates; update cache after a mutation; automatically update Apollo cache after mutation; updating client cache after mutation
我倾向于第一个链接中提到的方法,因为它是官方文档。
我的一些问题:
- 我是否遗漏了一些基本的东西?
- 这是一个简单的错误吗?就像某处提到的错误变量一样。
- 我需要在某处查询 GET_LINKS 吗?
下面是代码块供参考:
const [createLink] = useMutation(CREATE_LINK);
function handleSubmit(e) {
e.preventDefault();
createLink({
variables: {
slug: state.slug,
description: state.description,
link: state.link
},
update(cache, { data: { createLink } }) {
console.log(cache);
cache.modify({
fields: {
links(allLinks = []) {
const newLinkRef = cache.writeFragment({
data: createLink,
fragment: gql`
fragment NewLink on Link {
id
slug
description
link
shortLink
}
`
});
return [...allLinks, newLinkRef];
}
}
});
}
});
setState({
slug: "",
description: "",
link: ""
});
}
这是完整的代码库供参考: codesandbox.io
【问题讨论】:
-
mutation 总是失败('xxx 已经存在')然后没有调用
update... 突变不包含id然后片段确实没有所有必需的数据 ... 使用 readQuery,更简单...apollographql.com/docs/react/caching/cache-interaction/… -
嗨 xadm - 感谢您的想法。由于我后端的错误,突变总是失败。突变现在应该起作用了。但是更新不起作用。我从片段中删除了 id。现在应该更新工作吗?我现在正在阅读 readQuery。
-
allLinks(prevLinks = []) {asallLinks是一个“字段”,一个用于查询的缓存条目...插入debugger并探索缓存/数据/结构...需要“id”道具缓存 -
编辑了一些变量。添加了
id。你能详细说明一下领域吗?我目前收到gql is not defined错误。看起来引用错误可能是语法错误,但我不确定错误发生在哪里。 -
import { gql } from "@apollo/client";
标签: reactjs caching graphql apollo react-apollo