Skip to content

Instantly share code, notes, and snippets.

@tyteen4a03
Last active December 13, 2023 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyteen4a03/2708e1b57c8f2c904032cc1cceb9b007 to your computer and use it in GitHub Desktop.
Save tyteen4a03/2708e1b57c8f2c904032cc1cceb9b007 to your computer and use it in GitHub Desktop.
PayloadCMS Listener Field Pattern
{
name: "jobStopsListener",
type: "ui",
admin: {
components: {
Field: JobStopsListenerField,
},
},
},
import { gql, useQuery } from "@apollo/client";
import { useForm } from "payload/components/forms";
import { useDocumentInfo } from "payload/dist/admin/components/utilities/DocumentInfo";
import { Job } from "payload/generated-types";
import { useEffect } from "react";
import React from "react";
const WarehouseIdQuery = gql(/* GraphQL */ `
query WarehouseIdQuery {
Addresses(where: { type: { equals: warehouse } }) {
docs {
id
contactName
contactPhoneNumber
}
}
}
`);
const JobStopsListenerField = () => {
const { getDataByPath, addFieldRow } = useForm();
const stopsField: number | Job["stops"] = getDataByPath("stops");
const { versions } = useDocumentInfo();
const warehouseQuery = useQuery(WarehouseIdQuery);
useEffect(() => {
const warehouseId = warehouseQuery.data?.Addresses.docs[0].id;
// check stopsField for being a number; workaround for https://github.com/payloadcms/payload/issues/4477
if (!versions && (stopsField === 0 || (stopsField as Job["stops"]).length === 0) && warehouseId) {
// insert Warehouse as the first row, if no stops exist
addFieldRow({
data: {
address: warehouseId,
contactName: warehouseQuery.data?.Addresses.docs[0].contactName,
contactPhoneNumber: warehouseQuery.data?.Addresses.docs[0].contactPhoneNumber,
},
path: "stops",
});
}
}, [addFieldRow, warehouseQuery, stopsField, versions]);
return <></>;
};
export default JobStopsListenerField;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment