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.

Creating a custom component that copies content between locales of a document

default discord avatar
hesselberglast year

Hi everyone,



I'm trying to add a button to my document collections, where it provides a dropdown for the different locales of my config (excluding the currentLocale), which then ultimately when submitted lets you copy all the contents from one locale to another. This should ideally save some time for editors.



I'm struggling with how to communicate with the data of Payload, and whether I can use the local API or I need to create a custom end point that handles this.



Generally, is this the right approach, or have I missed a simpler way of doing this, ideally within Payload rather than custom endpoints?




// customComponent.tsx
export const CopyLocaleContentComponent: React.FC = () => {
  const { code: currentLocale } = useLocale();
  const { collectionSlug, id, isEditing } = useDocumentInfo();
  const [sourceLocale, setSourceLocale] = React.useState();

  const handleCopy = async () => {
    if (
      !id ||
      !collectionSlug ||
      !sourceLocale ||
      sourceLocale === currentLocale
    ) {
      return;
    }

    try {
      const response = await fetch(`/api/copy-locale`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          collection: collectionSlug,
          id,
          sourceLocale,
          targetLocale: currentLocale,
        }),
      });

      const result = await response.json();
      if (response.ok) {
        console.log('Content copied successfully!');
      } else {
        console.log(result.error || 'Failed to copy content.');
      }
    } catch (error: any) {
      console.log('Error occurred: ' + error.message);
    }
  };

  return (
    <div>
      <Select
        options={[...]}
        onChange={handleOnChange}
      />
      <Button onClick={handleCopy}>
        Copy
      </Button>
    </div>
  );
};


Found a solution that I think works well, in case anyone else stumbles on it.



* Create Payload endpoint in the payload collection configuration


* As part of copying data from one locale to another, if you are using a field of type 'blocks', e.g. for layout, you need to go through each block and set the

id

prop to

undefined

. Without knowing the exact reason why, one could assume this is due to the way content is stored in Postgres

    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.