I want to create a relationship in my Customer collection where the spouse should reference each other when set, so I came up with this hook:
hooks: {
beforeChange: [
async ({ data, value, previousValue, req: { payload } }) => {
if (!data || !data.id) return value;
if (
value &&
previousValue &&
getEntityId(value) === getEntityId(previousValue)
) {
return value;
}
if (value) {
await payload.update({
collection: "customers",
data: {
spouse: data,
},
id: isEntity(value) ? value.id : value,
});
} else {
await payload.update({
collection: "customers",
data: {
spouse: null,
},
where: {
spouse: { equals: data.id },
},
});
}
return value;
},
] satisfies FieldHook<
TypedCollection["customers"],
TypedCollection["customers"]["spouse"]
>[],
},
I tried it both as a beforeChange and afterChange hook, but no matter which one when saving the spouse the saving loads forever which leads me to believe that it's recursively calling the hook but I'm not sure why since I have the getEntityId(value) === getEntityId(previousValue) guard?