Description
I struggled for a bit getting updates to the store to work in a reactive way. I could see that update
on my $apollo.mutate
was being called, and could poke the store and see that the value changed in there, but it wasn't updating the UI. This was for a simple case of adding an item to a list, like the standard Todo example.
Only after defining an optimisticResponse
response on my $apollo.mutate
did things work as expected. I don't see anything in the documentation about this being required. Is this a requirement, or a bug?
I still can't get the delete mutation working with update
. Again, everything looks correct, but no UI update. Without the optimisticResponse
, nothing visually happens, with it, there's a flash as the item is removed, then put back. The response from the server is simply a boolean, and the optimistic response value is true
since I expect to to succeed. Switching that to false
(so that it actually differs from the server response) has no effect. However, changing anything in the code and letting HMR refresh the code, then trying the delete again succeeds.
Any suggestions?
export default {
data () {
return {
items: []
}
},
methods: {
async addItem () {
const input = { name: 'Test' }
try {
await this.$apollo.mutate({
mutation: ADD_ITEM_MUTATION,
variables: { input },
update: (store, { data: { addItem } }) => {
const data = store.readQuery({ query: ITEMS_QUERY })
data.items.push(addItem)
store.writeQuery({ query: ITEMS_QUERY, data })
},
optimisticResponse: {
__typename: 'Mutation',
addItem: {
__typename: 'Item',
id: null,
created: utils.currentTimestamp(),
...input
},
}
})
catch (err) {
console.log(err)
}
},
async deleteItem (item) {
const itemId = item.id
try {
await this.$apollo.mutate({
mutation: DELETE_ITEM_MUTATION,
variables: { itemId },
update: (store, { data: { deleteItem } }) => {
// Update the list of items
const data = store.readQuery({ query: ITEMS_QUERY })
const idx = data.items.indexOf(item)
if (idx) {
data.items.splice(idx, 1)
store.writeQuery({ query: ITEMS_QUERY, data })
}
},
optimisticResponse: {
__typename: 'Mutation',
deleteItem: true
}
})
} catch (err) {
console.log(err)
}
}
}
}