skip to Main Content

I am working on a react frontend for a woocommerce shop and I am currently trying to add an item to the cart with the selected option values ie size and color.

My current api call –

const AddToCart = async (id) => {
    let config = {
    method: "post",
    url: "/wp-json/wc/store/v1/cart/add-item",
    data: {
      id : id,
      quantity: 1,
      attributes: [
        {
        color: color
        },
        {
        size: size
     }]
    }
    }
   const resp = await axios(config).then((response) => {
    console.log(response.data)
  })
  .catch((error) => {
    console.log(error.response.data);
  });
  }

In the docs it says –

Chosen attributes (for variations) containing an array of objects with
keys attribute and value

However what I’ve tried is giving me this error –

code: "woocommerce_rest_variation_id_from_variation_data"
data: {status: 400}
message: "No matching variation found."

Example json response for single product –

   {
        "id": 933,
        .......    
        "attributes": [
            {
                "id": 1,
                "name": "Size",
                "position": 0,
                "visible": false,
                "variation": true,
                "options": [
                    "2XL",
                    "3XL",
                    "4XL",
                    "5XL",
                    "L",
                    "M",
                    "S",
                    "XL",
                    "XS"
                ]
            }
        ],
        "default_attributes": [],
        "variations": [
            936,
            937,
            938,
            939,
            940,
            941,
            942,
            943,
            944
        ],
      ...... 

2

Answers


  1. You have to pass the data like this:

    data: {
        id: id,
        quantity: 1,
        variation: [
            {
                attribute: "color"
                value: color,
            },
            {
                attribute: "size"
                value: size,
            }
        ]
    }
    

    As per documentation, variation accepts the array of objects and objects should have keys attribute and value.

    Login or Signup to reply.
  2. what’s wrong with this
    [{ attribute: ‘color’, value : selectedColor },{ attribute : ‘size’, value : selected }]

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search