I'm just starting to use GraphQL with Apollo and Vue, so it might be a "stupid" question but I can't figure how to do.
How can I do inside the same view, a query to fetch one object, and update it using a mutation
Let's say I have a simple schema
type Product {
id: ID!
title: String!
description: String
}
And a vue component
<script>
// GraphQL query
const ProductQuery = gql `
query($id: ID){
Product(id: $id)
{
id
title
description
}
}
`;
const UpdateProductQuery = gql `
mutation updateProduct($id: ID!, $title: String!, $description: String) {
updateProduct(
id: $id,
title: $title,
description: $description,
) {
id
}
}
`;
export default {
data() {
return {
Product: {},
};
},
apollo: {
Product: {
query: ProductQuery,
variables() {
id: 1234,
};
},
},
methods: {
updateProduct() {
this.$apollo.mutate({
mutation: UpdateProductQuery,
variables: {
id: this.Product.id,
title: this.Product.title,
description: this.Product.description,
},
})
}
}
};
</script>
Now how am I supposed to write the template part ? Can I link the Product object to a v-model inside an input ?
<template>
<section>
<input v-model="product.title"></input>
<input v-model="product.description"></input>
<button @click="updateProduct">Update</button>
</section>
</template>
Thanks for your help.
You're definitely on the right track! One thing I notice is that Product
is capitalized in your JS, but not in your template. So either update your template like so:
<template>
<section>
<input v-model="Product.title"></input>
<input v-model="Product.description"></input>
<button @click="updateProduct">Update</button>
</section>
</template>
...or make product
lowercase in your JS (which I personally prefer).
Also, I believe you need to use reactive parameters in this case. variables
will need to be a function rather than an object.
variables() {
return {
id: this.Product.id,
title: this.Product.title,
description: this.Product.description
}
}
Ok I finally found out that data from the query is immutable, that's why I can't update them.
The solution is to create a new object using Object.assign or lodash cloneDeep.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.