2

I have some legacy meta fields in my post that I would like to display in my block. I found a documentation for settings meta fields but not how to display them. So I tried this:

export default function save( { attributes } ) {

    const blockProps = useBlockProps.save();

    const postType = useSelect(
        ( select ) => select( 'core/editor' ).getCurrentPostType(),
        []
    );

    const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' );

    const game_meta = meta[ '_shortscore_game' ];

    return (
        <p { ...blockProps } >
            <h2><game_meta/></h2>
        </p>
    );
}

I get this error:

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

What is the problem? It happens because of

const postType = useSelect(
    ( select ) => select( 'core/editor' ).getCurrentPostType(),
    []
);

But why? It works the same in the edit function.

2 Answers 2

4

From the docs: https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#save

Note: The save function should be a pure function that depends only on the attributes used to invoke it. It can not have any side effect or retrieve information from another source, e.g. it is not possible to use the data module inside it select( store ).selector( ... ). This is because if the external information changes, the block may be flagged as invalid when the post is later edited (read more about Validation). If there is a need to have other information as part of the save, developers can consider one of these two alternatives:

  • Use dynamic blocks and dynamically retrieve the required information on the server.
  • Store the external value as an attribute which is dynamically updated in the block’s edit function as changes occur.
1
  • I used this: "Store the external value as an attribute which is dynamically updated in the block’s edit function as changes occur."
    – Marc
    Commented Nov 20, 2021 at 16:28
1

There is a plugin that allows displaying meta fields and ACF fields on the front-end as blocks here Meta Field Block. The requirement is your meta field has to enable the show_in_rest option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.