Hi folks,
I have been experimenting with Wix code, and I was trying to set up a button that creates a product (hard-coded info for now) and immediately adds it to the cart.
Something similar to this:
import { createProduct } from 'backend/products';
import { cart } from 'wix-stores';
// ...
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
//////////////////////////
////SET EXAMPLE PRODUCT
//////////////////////////
const myProduct = {
"name": "Colombian Arabica",
"description": "The best organic coffee that Colombia has to offer.",
"price": 35,
"pricePerUnitData": {
"totalQuantity": 100,
"totalMeasurementUnit": "G",
"baseQuantity": 1,
"baseMeasurementUnit": "G"
},
"sku": String(getRandomInt(999999999999999999)),
"visible": true,
"discount": {
"type": "AMOUNT",
"value": "5"
},
"productOptions": {
"Weight": {
"choices": [{
"value": "250g",
"description": "250g"
},
{
"value": "500g",
"description": "500g"
}
]
}
},
"manageVariants": true,
"productType": "physical",
"weight": 250,
"ribbon": "Organic",
"brand": "Coffee Company"
}
//////////////////////////
/////ON READY
//////////////////////////
$w.onReady(function () {
let prod_id
//create prod
$w("#button1").onClick(async () => {
//CREATE PRODUCT
const prod_id = await createProduct(myProduct)
.then((product) => {
// product created
const productId = product._id
console.log(productId);
const description = product.description
console.log(description);
return productId
})
.catch((error) => {
// product not created
console.error(error)
});
//CREATE CONST PROD ID
const products = [{
"productId": String(prod_id),
"quantity": 1,
"options": {
"choices": {
"Weight": "250g"
}
}
}]
console.log(prod_id);
//ADD IT TO CART
await cart.addProducts(products)
});
});
What I have observed is that if I try to run the code as is, it fails with stating that the product hasn’t been found; however if I add some other function (longer runtime) between the createProduct and cart.addProducts, it works right.
This makes me think that the problem is that the code tries to add the product before it’s fully created, despite all the awaits.
Does anyone know which might be the solution to not having to put another function between?
Many thanks in advance!!