假设我有以下GraphQL类型:
type User {
id: String!
posts: [Post!]!
}
type Post {
id: String!
text: String,
}下面是返回更新后的帖子的一个变异:
mutation addNewPost(
$userId: String!
$text: String!
) {
addNewPost(userId: $userId, text: $text) {
id
text
}
}在运行这个突变之后,我的缓存中包含了一个新的post条目。如何将其添加到用户的帖子数组中?我试过cache.writeQuery和cache.modify,但我搞不懂。
发布于 2021-11-15 11:06:36
我们确实在update函数中将项推入数组,这是useMutation的选项之一。我正在编写整个变异,这样你就可以理解了,让我们来看一下例子:
By Update函数:
const [createPost, { data, loading, error }] = useMutation(CREATE_POST, {
update(cache, response) {
// Here we write the update
// Step 1: Read/Fetch the data
const data = client.readQuery({
query: FETCH_POSTS_QUERY,
});
// Step 2: Update the cache by immutable way
client.writeQuery({
query: FETCH_POSTS_QUERY,
data: {
getPosts: [response.data.createPost, ...data.getPosts],
},
});
},
variables: formValues,
});refetchQueries提供的:
通过使用用gql函数解析的DocumentNode对象,这确实是更新缓存的捷径
const [createPost, { data, loading, error }] = useMutation(CREATE_POST, {
refetchQueries: [
FETCH_POSTS_QUERY
'fetchPosts`' // OR Query name
],
variables: formValues,
});发布于 2020-11-28 06:12:57
您可能希望直接写入Apollo缓存,以便更新您的突变修改过的其他实体。
请看这里的文档和细节(您将使用cache.modify和cache.writeFragment)。
https://stackoverflow.com/questions/65026151
复制相似问题