Skip to content

Hooks can't be used inside fieldTransforms #1251

@FedericoBonel

Description

@FedericoBonel

Description

Using any hooks inside field transforms throws an error. This includes copying and pasting the example of how to use field transforms from the docs, and also using the PuckAPI.

This might be happening because of the use of useMemo when initializing fieldTransforms here.

Environment

  • Puck version: 0.20.0

Steps to reproduce

  1. Copy and paste the "Making it interactive" example from the fieldTransforms docs, which uses two hooks (useEffect and useRef):
import { registerOverlayPortal } from "@measured/puck";

const EditableText = ({ value }) => {
  const ref = useRef(null);

  useEffect(() => {
    if (ref.current) {
      // Register the element as an overlay portal
      registerOverlayPortal(ref.current);
    }
  }, [ref.current]);

  return (
    // Mark the element as editable for inline text editing
    <p ref={ref} contentEditable>
      {value}
    </p>
  );
};

const fieldTransforms = {
  text: EditableText,
};

const Example = () => <Puck fieldTransforms={fieldTransforms} />;
  1. Add a config with a component that uses the transformed field (in this case, a text field):
const Example = () => (
  <Puck
    config={{
      components: {
        Heading: {
          fields: { title: { type: "text" } },
          defaultProps: { title: "Something" },
          render: ({ title }) => {
            return <div>{title}</div>;
          },
        },
      },
    }}
    fieldTransforms={fieldTransforms}
  />
);
  1. Navigate to the editor
  2. Drag and drop the component that uses the transformed field

What happens

An error is thrown:

Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. 
You can only call Hooks at the top level of your React function. 
For more information, see https://react.dev/link/rules-of-hooks

What I expect to happen

Hooks should be usable inside field transforms without breaking the application.

Additional Media

Image

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions