cart.addProducts not working with dynamic product Id.

Hi,
I created a custom private member page to display member’s requests and status of their requests. Also depending on the status, various buttons will be displayed for repeater items. I also placed 2 buttons on top of repeaters which display the data accordingly.

One of the buttons is add to cart, which when clicked creates the product and adds the same to the cart. The code worked fine till few days ago, but is not working now. Product is being created and the new product id is being fetched. But it is not being added to the cart i.e., cart.addProducts is not working. It works with a constant string but not with a dynamic value.

Any help regarding the same please. This is hindering my site functionality. Thanks in advance.

Can you post the code here, please?

This is the code that I used.
When I tried to debug, everything is working fine except the product not being added to the cart.

export async function placeOrder_click ( event ) {
let $item = $w . at ( event . context );
productCreation ( event )
. then (()=>{
Cart ( event );
$item ( ‘#NewProduct’ ). setFieldValue ( ‘status’ , ‘Request Processed’ );
$item ( “#NewProduct” ). save ()
. then (()=>{
$w ( “#NewProduct” ). refresh ();
checkStatus ( event );
})
})

}

async function productCreation ( event ){
let $item = $w . at ( event . context );
let title = ( $item ( ‘#text106’ ). text ) + ’ ’ + ‘(Customized)’ ;
let desciption = $item ( ‘#text116’ ). text ;
let subTotal = Number ( $item ( ‘#input1’ ). value );

**const**  product  = { 
  "name" :  title , 
  "description" :  desciption , 
  "price" :  subTotal , 
  "productType" :  "physical" , 
} 

**try** { 
    **let**  newProduct  =  **await**  createProduct ( product ); 
    newProductId  =  newProduct . _id ; 
} 
**catch** ( err ){ 
    $item ( '#errorProduct' ). show (); 
} 

}

async function Cart ( event ){
let $item = $w . at ( event . context );
const id = newProductId ;
const quantity = Number ( $item ( ‘#quantity’ ). value );

**const**  products  = [ 
{ 
    "productId" :  id , 
    "quantity" :  quantity 
}] 

cart . addProducts ( products ) 

. then (() => { 
// Only show the Mini Cart if the site is not being viewed on mobile 
**if**  ( formFactor  !==  "Mobile" ) { 
    cart . showMiniCart (); 
} 
}) 

. catch (( error ) => {
$item ( ‘#errorCart’ ). show ();
})
}

Can I see this createProduct() function?

I feel that there is a lot going on in this code, but I think it could be refactored to better its readability.

1 Like

createProduct() and cart.addProducts() are wix default functions I guess which I don’t have access to. I got these from the api reference.

1 Like

I saw some mistakes, try this code now:

export async function placeOrder_click(event, $item) {
    const newProduct = await productCreation(event)

    Cart(newProduct._id, Number($item("#quantity").value))

    $w("#NewProduct").setFieldValue("status", "Request Processed")
    $w("#NewProduct")
        .save()
        .then(() => {
            $w("#NewProduct").refresh()
            checkStatus(event)
        })
}

async function productCreation(event) {
    let $item = $w.at(event.context)
    let title = `${$item("#text106").text} (Customized)`
    let desciption = $item("#text116").text
    let subTotal = Number($item("#input1").value)

    const product = {
        name: title,
        description: desciption,
        price: subTotal,
        productType: "physical",
    }
    try {
        let newProduct = await createProduct(product)
        return newProduct
    } catch (err) {
        $item("#errorProduct").show()
    }
}

async function Cart(id, quantity) {
    const products = [
        {
            productId: id,
            quantity: quantity,
        },
    ]
    cart
        .addProducts(products)
        .then(() => {
            // Only show the Mini Cart if the site is not being viewed on mobile
            formFactor !== "Mobile" && cart.showMiniCart()
        })
        .catch(() => {
            $item("#errorCart").show()
        })
}

3 Likes

Thanks for writing. I tried the code but it still shows the same error(i.e., $item(‘#errorcart’).show() is getting triggered). I don’t understand where exactly it is going wrong.

1 Like

@infokalanidi so get the error with the .catch() method.

.catch((error)=>{
    console.log(error)
    $item("#errorCart").show()
})
1 Like

@bwprado
This is the error that is being showed.

Error: Invalid product id (should be a GUID)

Can you please help me with this?

1 Like

Thanks a lot for your support. Your code worked.
Now everything is sorted.

2 Likes

If you could please upvote the answer, would be great as more people would know that the answer was found.

Thanks.

2 Likes

Please I have a problem because when I click on the add to cart button (#addGranos), the mini cart is shown on the mobile, and that is what I want to avoid, please can you tell me what is wrong in the code why it continues to show the cart in the mobil.

$w.onReady(function () {

$w("#addGranos").onClick((event) => {
let $item = $w.at(event.context);
let selectedProduct = $item('#Granos').getCurrentItem();
let productId = selectedProduct._id;
let formFactor = wixWindow.formFactor; // "Mobile"
$w('#shoppingCartIcon1').addToCart(productId)
.then(() => {

    if (formFactor !== "Mobile") {
        cart.hideMiniCart();
    }

console.log("add product ${productId} success");
})

.catch((error) => {
    console.log(error)
});
});
});