Last active
February 20, 2019 12:08
-
-
Save CodingItWrong/590acf86a5bfce16a61cc9de9a23c520 to your computer and use it in GitHub Desktop.
Vue-Apollo Update
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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