how to add product to shop cart via apollo and react

how to add product to shop cart via apollo and react


0

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

Vasilii is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.


Load 7 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *