[英]Optimistic UI Not Updating - Apollo
進行突變后,直到刷新頁面后,UI才會使用新添加的項目進行更新。 我懷疑問題出在突變的更新部分,但是我不確定如何進一步解決問題。 任何建議深表感謝。
查詢(單獨的文件)
//List.js
export const AllItemsQuery = gql`
query AllItemsQuery {
allItems {
id,
name,
type,
room
}
}
`;
突變
import {AllItemsQuery} from './List'
const AddItemWithMutation = graphql(createItemMutation, {
props: ({ownProps, mutate}) => ({
createItem: ({name, type, room}) =>
mutate({
variables: {name, type, room},
optimisticResponse: {
__typename: 'Mutation',
createItem: {
__typename: 'Item',
name,
type,
room
},
},
update: (store, { data: { submitItem } }) => {
// Read the data from the cache for this query.
const data = store.readQuery({ query: AllItemsQuery });
// Add the item from the mutation to the end.
data.allItems.push(submitItem);
// Write the data back to the cache.
store.writeQuery({ query: AllItemsQuery, data });
}
}),
}),
})(AddItem);
看起來很有希望,錯誤的一件事是突變data: { submitItem }
的結果名稱data: { submitItem }
。 因為在樂觀的Response中,您將其聲明為createItem
。 您是否進行過console.log,並且突變是什么樣的?
update: (store, { data: { submitItem // should be createItem } }) => { // Read the data from our cache for this query. const data = store.readQuery({ query: AllItemsQuery }); // Add our comment from the mutation to the end. data.allItems.push(submitItem); // also here // Write our data back to the cache. store.writeQuery({ query: AllItemsQuery, data }); }
我不能完全確定問題出在上面的optimisticResponse
函數上(這是正確的方法),但是我想您使用的是錯誤的返回值。 例如,這是我們正在使用的響應:
optimisticResponse: {
__typename: 'Mutation',
updateThing: {
__typename: 'Thing',
thing: result,
},
},
因此,如果不得不大膽猜測,我會說您可能想嘗試在返回值中使用該類型:
optimisticResponse: {
__typename: 'Mutation',
createItem: {
__typename: 'Item',
item: { // This was updated
name,
type,
room
}
},
},
另外,您也可以refetch
。 在我們的代碼庫中,有幾次情況只是沒有更新我們希望它們的方式,我們無法弄清楚為什么要這樣做,所以我們平底鍋,只是在突變解決后重新提取(突變返回一個承諾!)。 例如:
this.props.createItem({
... // variables go here
}).then(() => this.props.data.refetch())
第二種方法應該每次都起作用。 這並不完全樂觀,但這會導致您的數據更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.