I try to use useMutation
to add product to cart by button click, but after a lot of attempts it still don’t work and i can’t understand how to make it work.
my code looks like that:
product.jsx
const [add, {error: addError}] = useMutation(ADD_CART, {
update(cache, { data: { add } }) {
cache.modify({
fields: {
getAllCart(currentCart = []) {
return currentCart.filter(todo => todo.__ref !== `Cart:${add.id}`)
}
}
})
}
});
and button
<Button onClick={() => add({variables: {id: productId, size: size.id }})} >Add to Cart</Button>
query
export const ADD_CART = gql`
mutation AddCart ($id: Int) {
addCart(id: $id) {
id, title, text, size, price, image
}
}`
in bff:
index.js
addCart: (args) => {
carts = carts.filter((c) => c.id !== args.id);
return carts;
},
schema.js
type Mutation {
addCart(id: Int): [Cart]
}
Thank you in advance!
New contributor