I’m having problems getting a beforeInsert() hook to work and would appreciate any suggestions.
I’ve got a collection named dinnerOrders on which I’m trying to add a unique order number right before each new record is inserted. I’ve got a separate collection named orderNumber with one row in it, with a field containing the nextOrderNumber. So, I’m trying to use the hook to read nextOrderNumber from the orderNumber collection and then set the orderNumber field in the dinnerOrders collection equal to it before insert.
Here’s my current code in data.js:
import wixData from 'wix-data';
export function dinnerOrders_beforeInsert(item, context) {
wixData.get("orderNumber", "a0d8fc69-9b8a-46d5-a066-f4fe67faf430").then((record) => {
item.orderNumber = record.nextOrderNumber;
console.log("Order Number = " + record.nextOrderNumber);
});
return item;
}
I know that the read is working because the correct nextOrderNumber is logged to the console. I also know that the hook is working because when I just set item.orderNumber equal to a constant outside the GET it gets written to the collection just fine. So, I seem to be missing something fundamental about how promises or variable scope or something like that works.
Please pardon me if this is newbie question – I’m probably missing a straightforward answer.
Thanks for any ideas, either on this code specifically or on a different approach to accomplish the same thing. If only there was an “AutoNumber” data type available in collections, like Access.