Moralis.Cloud.beforeSave is running twice

Good day!

Why is the beforeSave being triggered twice whenever a transaction is made?

Moralis.Cloud.beforeSave("ItemsSold", async (request) => {

    const query = new Moralis.Query("ItemsForSale");
    query.equalTo("itemId", request.object.get('itemId'));
    const item = await query.first();
    if (item) {
        request.object.set('item', item);
        let x = Number(item.get("soldNFTs")) + Number(request.object.get('amount'))
        item.set('soldNFTs', x.toString());
        if (x.toString() === item.get("amount"))
            item.set('sold', true);
        await item.save();
    }
});

If you save the object in before save then that could be a reason. It could also enter an infinite loop if there is no check.

Another possible reason could be if the transaction is synced once as unconfirmed and once as confirmed

I still use the Syncs Events feature of Moralis Servers.

In the second reason, do you mean that it is also being triggered if the item is updated?

It is triggered any time the item is updated

Usually you can use a flag to know if the code that you want to run was executed or not. You add a separate column in that table in order to store that flag

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.