I’ve inherited a Payload CMS project and I have a component like this.
I want to get the the defaultValue, which is a global string, and show it as the description value. Then you don’t have to navigate to the global string page to see what it is.
export const CardInstructionTitle: Field = {
type: "row",
fields: [
{
name: "title",
type: "group",
fields: [
{
name: "default",
type: "checkbox",
label: "Use Default Instruction",
defaultValue: true,
admin: {
description: `The default value is: ${defaultValue} (it would be great if this worked) `,
},
},
{
name: "text",
type: "text",
admin: {
components: {
Field: Component,
},
},
localized: true,
},
],
},
],
};
CardInstructionTitle is used by a few different Block types, so I pass the name of the block like this…
export const SelectThePairsCard: Block = {
slug: "selectThePairs",
interfaceName: "SelectThePairsFields",
fields: [
CardInstructionTitle("selectThePairs"),
{
name: "wordPairs",
type: "array",
fields: [
{
type: "row",
fields: [
{
name: "firstWord",
type: "text",
},
{
name: "secondWord",
type: "text",
},
],
},
],
},
],
};
…and use this string to fetch the defaultValue.
const getDefaultValue = async (defaultTitle) => {
let locale = "fr"
try {
const response = await fetch(`/payload/api/globals/cardInstructionTitles?locale=${locale}`);
if (!response.ok) {
throw new Error(`Failed to fetch: ${response.statusText}`);
}
const data = await response.json();
const value = data[defaultTitle];
if (typeof value !== 'string') {
throw new Error(`Invalid default value for ${defaultTitle}`);
}
return value;
} catch (error) {
console.error(`Error fetching default value: ${error.message}`);
return `Error fetching value for ${defaultTitle}`;
}
};
And put it in CardInstructionTitle
export const CardInstructionTitle: (parentName: string) => Field = (parentName: string) => {
return {
type: "row",
fields: [
{
name: "title",
type: "group",
fields: [
{
name: "default",
type: "checkbox",
label: "Use Default Instruction",
defaultValue: true,
admin: {
description: getDefaultValue(parentName),
}
},
{
name: "text",
type: "text",
admin: {
components: {
Field: Component,
},
},
localized: true,
},
],
},
],
}
};
Except that it doesn’t seem that the description field is allowed to accept an async value because I keep getting an error saying it’s:
The types of 'admin.description' are incompatible between these types.
Type 'Promise<string>' is not assignable to type 'Description | undefined'.
Type 'Promise<string>' is not assignable to type 'Record<string, string>'.
Index signature for type 'string' is missing in type 'Promise<string>'.
So, is there a better way to do this? Logically it seems like the defaultValue must be available nearby but how do I assign it to the description, or should I do another approach, like create a new component that just displays defaultValues?
I’m new to Payload and TypeScript so any help would be greatly appreciated, Thanks.
It is Payload version 2