Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Updating Y collection after Z has changed

default discord avatar
_elmgrenlast year
1

Hello! I have a bookings collection, and a payment settings collection. The booking collection has a

paymentSettingsReference

field.



I have a

beforeChange

hook on booking collection to run a totalPrice logic based on the payment setting.



Now I want to trigger this

beforeChange

hook whenever a payment setting is updated as well to keep them in sync.



What is best practice here? I tried updating it with a

afterChange

hook in my payment settings collection, but the

payload.update

promise doesn't resolve so it hangs.



const updateBookingsHook = async (payload: Payload) => {
  await payload.update({
    collection: 'bookings',
    where: {
      status: { equals: 'confirmed' }, // Only confirmed bookings
    },
    data: {}, // Empty data to trigger beforeChange hook
  });
};

export const updateBookingsAfterPaymentSettingChangeHook: CollectionAfterChangeHook =
  async ({ req }) => {
    await updateBookingsHook(req.payload).catch((e: unknown) => {
      console.error('Error updating bookings:', e);
    });
  };


This is the beforeChange hook:


import { CollectionBeforeChangeHook } from 'payload';
import { Booking } from '../../payload-types';
import { calculateTotalPrice } from '../utils/calculateTotalBookingPrice';

export const bookingBeforeChangePriceHook: CollectionBeforeChangeHook<
  Booking
> = async ({ data, req }) => {
  const { date, players, discountReference } = data;

  if (!date || !players) {
    return data;
  }

  // Calculate total price
  const { totalPrice, paymentReference } = await calculateTotalPrice(
    req.payload,
    {
      date,
      players,
      discountReference,
    }
  );

  return { ...data, totalPrice, paymentReference };
};
  • default discord avatar
    devskadlast year

    Can you share the code for the booking and payment functionality in payloadcms?

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.