Hi All,
I’ve got some code that creates a custom product based on user input, it creates the product, then goes on to add the product to the cart.
However, it appears, it’s trying to add it to the cart, before it’s been completely created. The following code is much simplified but shows the error:
/*******************************
* Backend code - products.jsw *
*******************************/
import wixStoresBackend from 'wix-stores-backend';
export function createProduct(product) {
return wixStoresBackend.createProduct(product);
}
/*******************************
* Page code *
*******************************/
import {createProduct} from 'backend/products';
$w.onReady(function () {
$w("#addToCartButton").onClick(async () => {
const product = {
"name": "Test Product",
"description": "Description for test product.",
"price": 149.99,
"productType": "physical",
}
try {
let newProduct = await createProduct(product);
// Product was created, add it to cart...
const productID = newProduct._id;
const productDescription = newProduct.description;
console.log('Product created:')
console.log(productID)
console.log(productDescription)
$w('#shoppingCartIcon1').addToCart(productID)
.then( () => {
console.log("Product added");
} )
.catch( (error) => {
console.log('Product not added:');
console.log(error);
} );
}
catch (err) {
// Product was not created...
console.log('Product not created:')
console.log(err)
}
});
})
The custom product is created fine, but it fails to be added to the cart as it can’t be found:
Console log results:
Product created:
981db17f-720e-495c-aff4-74e3388763ff
Description for test product.
Product not added:
FetchError: {"code":"CANNOT_ADD_CART","commandName":"AddToCart","message":"Product with id 981db17f-720e-495c-aff4-74e3388763ff was not found","field":""}
If I rerun the page, but instead of using the variable if I use the ID for the previously created product, it works! So the product is created, but the timing appears that it’s attempted to add to cart before it’s finalised being created.
If I add a setTimeout delay of 1 second, before adding the product to the cart, it works fine, with the productID.
So adding a delay between creating the product and adding it to the cart does work, but it feels a kludge!
I was hoping using the async and then await createproduct… would mean that it wouldn’t add it to the cart until the product was fully created?
Any help, feedback or comments are most appreciated, many thanks for your help.
Cheers,
Andy.