Sve*_*ven 0 apollo graphql apollo-client
假设我有以下 GraphQL 类型:
type User {
id: String!
posts: [Post!]!
}
type Post {
id: String!
text: String,
}
Run Code Online (Sandbox Code Playgroud)
这是返回更新后的帖子的突变:
mutation addNewPost(
$userId: String!
$text: String!
) {
addNewPost(userId: $userId, text: $text) {
id
text
}
}
Run Code Online (Sandbox Code Playgroud)
运行此突变后,我的缓存包含帖子的新条目。如何将其添加到用户的帖子数组中?我尝试过cache.writeQuery和cache.modify但我无法弄清楚。
我们确实将项目推送到更新函数内的数组中,这是 useMutation 的选项之一。我正在写整个突变,以便您能够理解,让我们看一下示例:
通过更新功能:
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,
});
Run Code Online (Sandbox Code Playgroud)
通过 refetchQueries:
这确实是更新缓存的快捷方式,通过使用 gql 函数解析的 DocumentNode 对象
const [createPost, { data, loading, error }] = useMutation(CREATE_POST, {
refetchQueries: [
FETCH_POSTS_QUERY
'fetchPosts`' // OR Query name
],
variables: formValues,
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3093 次 |
最近记录: |