当初始查询响应不包含所需的__typename时,可以使用urql更新GraphQL缓存的方法如下:
updates
选项来定义更新缓存的逻辑。updates
是一个函数,它接收一个参数cache
,代表当前的缓存实例。updates
函数中,可以使用cache.modify
方法来更新缓存。cache.modify
接收一个对象参数,其中包含fields
属性,用于指定要更新的字段。fields
属性中,可以使用GraphQL的查询路径来指定要更新的字段。例如,如果要更新User
类型下的name
字段,可以使用User.name
作为路径。fields
属性中,可以使用readField
方法来读取缓存中的字段值。readField
接收两个参数,第一个参数是要读取的字段路径,第二个参数是一个可选的上下文对象。fields
属性中,可以使用writeField
方法来写入缓存中的字段值。writeField
接收三个参数,第一个参数是要写入的字段路径,第二个参数是要写入的值,第三个参数是一个可选的上下文对象。writeField
方法中,可以使用typename
属性来指定要写入的字段的类型。这样可以确保缓存中的字段类型正确。writeField
方法中,可以使用merge
选项来指定如何合并新值和旧值。merge
选项是一个函数,它接收两个参数,分别是旧值和新值,返回合并后的值。综上所述,使用urql更新GraphQL缓存的步骤如下:
updates
函数。updates
函数中使用cache.modify
方法更新缓存。fields
属性中使用readField
方法读取缓存中的字段值。fields
属性中使用writeField
方法写入缓存中的字段值,并指定字段的类型。merge
选项指定如何合并新值和旧值。以下是一个示例代码:
import { createClient, dedupExchange, cacheExchange } from 'urql';
import { gql } from '@urql/core';
const client = createClient({
url: 'https://api.example.com/graphql',
exchanges: [
dedupExchange,
cacheExchange({
updates: {
Mutation: {
updatePost: (result, args, cache, info) => {
cache.modify({
fields: {
Post: (existingPost, { readField, writeField }) => {
const newPost = writeField('title', args.title, {
typename: 'Post',
merge: (oldValue, newValue) => newValue,
});
return newPost;
},
},
});
},
},
},
}),
],
});
const UPDATE_POST = gql`
mutation UpdatePost($id: ID!, $title: String!) {
updatePost(id: $id, title: $title) {
id
title
}
}
`;
client
.mutation(UPDATE_POST, { id: '123', title: 'New Title' })
.toPromise()
.then((result) => {
// Mutation completed
});
在上述示例中,我们定义了一个updatePost
的mutation,并在updates
函数中使用cache.modify
方法更新缓存。在fields
属性中,我们使用writeField
方法将新的title
值写入缓存中的Post
字段,并指定字段的类型为Post
。
领取专属 10元无门槛券
手把手带您无忧上云