Skip to content

Instantly share code, notes, and snippets.

@CodingItWrong
Last active February 20, 2019 12:08
Show Gist options
  • Save CodingItWrong/590acf86a5bfce16a61cc9de9a23c520 to your computer and use it in GitHub Desktop.
Save CodingItWrong/590acf86a5bfce16a61cc9de9a23c520 to your computer and use it in GitHub Desktop.
Vue-Apollo Update
// see https://vue-apollo.netlify.com/guide/apollo/mutations.html
{
addTag() {
// We save the user input in case of an error
const newTag = this.newTag
// We clear it early to give the UI a snappy feel
this.newTag = ''
// Call to the graphql mutation
this.$apollo.mutate({
// Query
mutation: gql`mutation ($label: String!) {
addTag(label: $label) {
id
label
}
}`,
// Parameters
variables: {
label: newTag,
},
// Update the cache with the result
// The query will be updated with the optimistic response
// and then with the real result of the mutation
update: (store, { data: { addTag } }) => {
// Read the data from our cache for this query.
const data = store.readQuery({ query: TAGS_QUERY })
// Add our tag from the mutation to the end
data.tags.push(addTag)
// Write our data back to the cache.
store.writeQuery({ query: TAGS_QUERY, data })
},
// Optimistic UI
// Will be treated as a 'fake' result as soon as the request is made
// so that the UI can react quickly and the user be happy
optimisticResponse: {
__typename: 'Mutation',
addTag: {
__typename: 'Tag',
id: -1,
label: newTag,
},
},
}).then((data) => {
// Result
console.log(data)
}).catch((error) => {
// Error
console.error(error)
// We restore the initial user input
this.newTag = newTag
})
},
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment