Skip to content

Commit

Permalink
Merge pull request #263 from 10up/fix/make-has-supported-meta-value-c…
Browse files Browse the repository at this point in the history
…ontext-aware

Fix: Make `useIsSupportedMetaField` hook context aware
  • Loading branch information
fabiankaegy authored Sep 20, 2023
2 parents 8736c74 + 94010d5 commit 29aba18
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 14 deletions.
4 changes: 4 additions & 0 deletions example/src/blocks/post-meta/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,9 @@
"default": ""
}
},
"usesContext": [
"postId",
"postType"
],
"editorScript": "file:./index.js"
}
9 changes: 6 additions & 3 deletions example/src/blocks/post-meta/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ import {
store as blockEditorStore,
} from '@wordpress/block-editor';
import { useSelect, useDispatch } from '@wordpress/data';
import { PostMeta } from '@10up/block-components';
import { PostMeta, PostContext } from '@10up/block-components';

export const BlockEdit = (props) => {
const { attributes, setAttributes, name } = props;
const { attributes, setAttributes, name, context } = props;
const { postId, postType } = context;
const { metaKey } = attributes;
const blockProps = useBlockProps();

Expand Down Expand Up @@ -46,7 +47,9 @@ export const BlockEdit = (props) => {

return (
<div {...blockProps}>
<PostMeta metaKey={metaKey} placeholder="Meta Value" />
<PostContext postId={postId} postType={postType}>
<PostMeta metaKey={metaKey} placeholder="Meta Value" />
</PostContext>
</div>
);
};
19 changes: 8 additions & 11 deletions hooks/use-is-supported-meta-value/index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import { useSelect } from '@wordpress/data';
import { store as editorStore } from '@wordpress/editor';
import { useEntityRecord } from '@wordpress/core-data';
import { usePost } from '../use-post';

export const useIsSupportedMetaField = (metaKey) => {
return useSelect(
(select) => {
const meta = select(editorStore).getCurrentPostAttribute('meta');
const supportedMetaKeys = Object.keys(meta || {});
const isSupportedMetaField = supportedMetaKeys?.some((name) => name === metaKey);
return [!!isSupportedMetaField];
},
[metaKey],
);
const { postId, postType } = usePost();
const { record } = useEntityRecord('postType', postType, postId);
const { meta } = record || {};
const supportedMetaKeys = Object.keys(meta || {});
const isSupportedMetaField = supportedMetaKeys?.some((name) => name === metaKey);
return [!!isSupportedMetaField];
};

0 comments on commit 29aba18

Please sign in to comment.