I have this code adding repeater items to another database.
export async function checkout_click(event, $w) {
let user = wixUsers.currentUser;
let userId = user.id;
let count = $w("#dataset1").getTotalCount();
wixData.query("Cart") // get the item from the database collection.
.eq("userId", userId)
.find()
.then((results) => {
let items = results.items;
confirm(results.items);
});
}
async function confirm(items) {
items.forEach(async (item, i) => {
await wixData.insert("JobBoard", item);
await wixData.remove("Cart", items[i]._id);
wixLocation.to("/success");
})
}
I have an input element outside the repeater where the user will key in their email address. I want this input element to go into the database along with the above items.
async function confirm(items) {
items.forEach(async (item) => {
await wixData.insert("JobBoard", item); // This will break because you have an _id coming in your items array from the cart query results.
await wixData.remove("Cart", items._id); // Do no use [i] in forEach, not necessary
wixLocation.to("/success");
})
}
So try out this instead
async function confirm(items) {
items.forEach(async (item) => {
let toInsert = item;
toInsert._id = null;
await wixData.insert("JobBoard", toInsert); // Just make sure you have all the fields here
await wixData.remove("Cart", items._id); //
wixLocation.to("/success");
})
}
You could also use promises like wixData.insert(“JobBoard”, toInsert).then((res) => { //Do you other remove here and then in that promise do the wixLocation redirect.})
You could also use promises like wixData.insert(“JobBoard”, toInsert).then((res) => { //Do you other remove here and then in that promise do the wixLocation redirect.})
Yisrael said we cannot use .then and await together. Do you think this is gonna cause trouble here ?