Reputation: 704
I have a react app Im working on to create a new frontend for an already live woocommerce site. I'm using this endpoint /wp-json/wc/store/v1/cart/add-item
like so -
let config = {
method: "post",
url: "http://localhost:8010/proxy/wp-json/wc/store/v1/cart/add-item",
data: {
id : id,
quantity: 1,
variation: [
{
attribute: "Color",
value: color,
},
{
attribute: "Size",
value: size,
}
]
}
}
console.log(config)
const resp = await axios(config).then((response) => {
console.log(response.data)
})
.catch((error) => {
console.log(error.response.data);
});
Which is giving me a successful json response showing I have the item added -
items_count: 1
Then I have a cart component to api call and render -
useEffect(() => {
getCart();
}, []);
const getCart = async () => {
let config = {
method: "get",
url: "http://localhost:8010/proxy/wp-json/wc/store/v1/cart"
}
await axios(config).then((response) => {
console.log(response.data)
})
.catch((error) => {
console.log(error.response.data);
});
}
However when navigating to this page/component or any other, the api call is returning an empty cart - items_count: 0
On the checkout page I tried using a different endpoint wp-json/wc/store/v1/checkout
but this is giving me an error -
code: "woocommerce_rest_cart_empty" data: {status: 400} message: "Cannot create order from empty cart."
Any ideas why this is happening?
Upvotes: 1
Views: 1421
Reputation: 121
When working with woocommerce Store Api you need to use "cart-token"
now, as woo developers says in comments at github and their blog, you also need consider cors as well. Check article and comments https://developer.woocommerce.com/2023/09/20/tutorial-placing-an-order-using-the-store-api/#comment-30550
Upvotes: 1
Reputation: 91
It's possible that the request isn't setting a cookie which will prevent the cart from working as expected. In my experience, I can make a build of my React app and activate it as a WordPress theme. Then the add-to-cart works as expected. But if I'm using the live preview of the app instead, the add-to-cart will not work because the cookie is missing. Here's a GitHub issue about it.
https://github.com/woocommerce/woocommerce-blocks/issues/5683
Upvotes: 2