Hello! I have a repeater with dataset from Product collection. I create click handler of button and I want adding product to cart, but i get error - $w().addToCart() is not a function.
Following code of click handler
export function button5_click(event) {
const $repeater = $w.at(event.context);
const productId = $repeater("#dataset1").getCurrentItem()._id;
$w('#shoppingCartIcon1').addToCart(productId, 1)
.then( () => {
console.log("Product added");
} )
.catch( (error) => {
console.log(error);
} );
}
Please, help me with problem, because i don’t understant that i do not right. Thanks!
Thanks for answer. I write this code accepting articles that you take me, but now I get error in browser console:
Code
$w.onReady(function () {
$w.onReady(function () {
$w("#button5").onClick((event) => {
let $item = $w.at(event.context);
let selectedProduct = $item('#dataset1').getCurrentItem();
let productId = selectedProduct._id;
$w('#Cart').addToCart(productId)
.then(() => {
console.log("add product ${productId} success");
})
.catch((error) => {
console.log(error);
});
});
});
});
Error
Uncaught (in promise) TypeError: $w(…).addToCart is not a function
at ids0f.js?viewMode=pr…682.eyJpbnN0YW5…:44
at postMessage_onMessage (wixcode-worker.js:18)
at InternalAPIs.value (wixcode-worker.js:18)
at delegateMessageToSDK (wixcode-worker.js:1)
at wixcode-worker.js:1
at tryCatch (wixcode-worker.js:1)
at Generator._invoke (wixcode-worker.js:1)
at Generator.e. [as next] (wixcode-worker.js:1)
at asyncGeneratorStep (wixcode-worker.js:1)
at _next (wixcode-worker.js:1)
at wixcode-worker.js:1
at new Promise ()
at _processMessage (wixcode-worker.js:1)
at wixcode-worker.js:1
at Object.handle (wixcode-worker.js:18)
at wixcode-worker.js:1
at self.onmessage (wixcode-worker.js:1)
I’m not understanding this error beacause i am following the instruction, but method not defined. OMG, how work this magic corvid API!
The code will not work as you do not have it set properly, see CartIcon in the Wix API Reference and you will see your error.
https://www.wix.com/corvid/reference/$w.CartIcon.html#addToCart
You are getting this error as you are not using the correct code to go with the Cart Icon element as Steve correctly mentioned in the linked post.
So, to correct your code you will need to do this:
-
Take off the first onReady function as you only need the one on your page;
-
Change #Cart to #shoppingCartIcon1;
-
Take off the last line of curly bracket, parenthesis and semi colon as it is not needed.