问题描述
突变的结果应该更新数据,而不需要向服务器发出不必要的请求,我不明白需要更正什么,以便数据不会被获取两次,而是从缓存中取出。
const [createEvent,{ loading }] = useMutation(CREATE_GOOD_MUTATION,{
variables: values,update(proxy,result) {
// Todo: remove goods from cache
const data = proxy.readQuery({
query: FETCH_ITEMS_QUERY,});
let newData = [...data.events];
newData = [result.data.events,...newData];
proxy.writeQuery({
query: FETCH_ITEMS_QUERY,data: {
...data,events: {
newData,},});
},// refetchQueries: [
// {
// query: FETCH_ITEMS_QUERY,// },// ],onError(err) {
setErrors(err.message);
},});
突变以创造新的商品:
CREATE_GOOD_MUTATION = gql`
mutation createEvent(
$title: String!
$description: String!
$price: String!
$autor: String!
$pageNumber: String!
$publishYear: String!
) {
createEvent(
eventInput: {
title: $title
description: $description
price: $price
autor: $autor
pageNumber: $pageNumber
publishYear: $publishYear
}
) {
title
description
price
}
}
`;
FETCH_ITEMS_QUERY = gql`
query events {
events {
id
title
description
price
}
}
`;
我需要获取一次,当我尝试通过突变创建新商品并显示缓存中的所有产品时,无需额外请求。
解决方法
您应该使用 proxy.modify
而不是 proxy.readQuery
/proxy.writeQuery
。
Making cache updates with mutation.update function
尝试将您的突变 update
函数更改为如下所示:
update(proxy,result) {
proxy.modify({
fields: {
events(existingEvents = []) {
return [...existingEvents,result.data.createEvent];
}
}
})
},