Incrementing items by drag and drop

I'm trying to handle incrementing item quantities rather than adding new items when you drag and drop an item to a character sheet, as long as the item already exists in their inventory and is of the right type. I've set up a hook in my ready hook section (using the Boilerplate as a base) but now it's both incrementing the existing item and adding a brand new one.
  Hooks.on("preCreateItem", async (item, options, userId) => {
    const actor = item.parent;

    // Define the item types that should have quantity incremented
    const incrementableTypes = ["gear", "consumable", "scroll", "lootbox"];

    // Check if the item type is one where the quantity should be incremented
    if (incrementableTypes.includes(item.type)) {
      // Find if the actor already has an item with the same name and type
      const existingItem = actor.items.find(i => i.name === item.name && i.type === item.type);

      if (existingItem) {
        // Increment the quantity of the existing item
        const newQuantity = (existingItem.system.quantity || 1) + (item.system.quantity || 1);

        // Update the existing item's quantity
        await existingItem.update({ "system.quantity": newQuantity });

        // Prevent creating a new item
        return false;
      }
    }

    return true;
  });
  Hooks.on("preCreateItem", async (item, options, userId) => {
    const actor = item.parent;

    // Define the item types that should have quantity incremented
    const incrementableTypes = ["gear", "consumable", "scroll", "lootbox"];

    // Check if the item type is one where the quantity should be incremented
    if (incrementableTypes.includes(item.type)) {
      // Find if the actor already has an item with the same name and type
      const existingItem = actor.items.find(i => i.name === item.name && i.type === item.type);

      if (existingItem) {
        // Increment the quantity of the existing item
        const newQuantity = (existingItem.system.quantity || 1) + (item.system.quantity || 1);

        // Update the existing item's quantity
        await existingItem.update({ "system.quantity": newQuantity });

        // Prevent creating a new item
        return false;
      }
    }

    return true;
  });
2 Replies
Ethaks
Ethaks3mo ago
Hook callbacks are not awaited. Making one async will result in its result becoming Promise<boolean> instead of boolean, and that Promise will always be truthy, thus not preventing the creation of an item. If you're doing this within a system, you might also want to check out the document's Item#_preCreate, which is awaited. Consideration as to whether this handling should be part of the drag and drop handling instead of all item handling might also apply.
Saverian
SaverianOP3mo ago
Aaaah, right ok. Yeah I'm building out a system so I've looked in to drag and drop handling and got it working that way, thanks for that!
Want results from more Discord servers?
Add your server