I am writing code to allow a user to manage the images in a store product. I am getting inconsistent results. I display the images on the page allowing the order to be manipulated, deleted or new uploads. That all works great. At the end of the operation the save button is hit and the images on the screen are saved using the addProductMedia function. They do not save in any consistent order. For example, one time image 1 will save in mediaItems[0] and other times image 1 will save in mediaItems[1]. Other times the same code will do it properly.
Any ideas? The issue seems to be that the addProductMedia returns a promise so doing 3 adds in a row results in inconsistent results. Here is the simple code:
// Erase the current images
removeProductMedia(product_id) // not passing media will remove all media from product
// Add the current main product into ProductMedia
let mainSrc = $w('#image').src;
if (mainSrc != ""){
let mainMediaData = [{src:$w("#image").src}]
console.log("Main media file:" + mainSrc);
await addProductMedia(product_id,mainMediaData);
// Move each populated image into ProductMedia ... At this time choice and option are not supported ... future update
for (let index = 1; index < 7; index++) {
let src = $w("#image" + index).src;
if (src != "") {
let mediaData = [{ // add media item to a choice
src
}]
console.log("Image media" + index +": " + src);
await addProductMedia(product_id,mediaData);
}
}
}
}
/*******************************
* Backend code - products.jsw *
*******************************/
import wixStoresBackend from 'wix-stores-backend';
export async function addProductMedia(productId, mediaData) {
return await wixStoresBackend.addProductMedia(productId, mediaData);
}
export function removeProductMedia(productId, media) {
return wixStoresBackend.removeProductMedia(productId, media);
}