Skip to content

Instantly share code, notes, and snippets.

@torounit
Last active September 1, 2020 03:28
Show Gist options
  • Save torounit/658fc871940c89ce0ea194392ab5ef2e to your computer and use it in GitHub Desktop.
Save torounit/658fc871940c89ce0ea194392ab5ef2e to your computer and use it in GitHub Desktop.
useState 風味に WordPressのカスタムフィールドを扱うやつ
import { Fragment, useCallback } from '@wordpress/element';
import { useDispatch, useSelect } from '@wordpress/data';
const useMeta = ( key ) => {
const meta = useSelect( ( select ) => {
const { getEditedPostAttribute } = select( 'core/editor' );
const values = getEditedPostAttribute( 'meta' ) || {};
return values[ key ] || '';
}, [] );
const { editPost } = useDispatch( 'core/editor' );
const setMeta = useCallback( ( value ) => {
editPost( {
meta: { [ key ]: value },
} );
}, [] );
return [ meta, setMeta ];
};
import { Fragment, useCallback } from '@wordpress/element';
import { useDispatch, useSelect } from '@wordpress/data';
const useMeta = <T extends any>( key: string ): [ T, ( v: T ) => void ] => {
const meta = useSelect( ( select ) => {
const { getEditedPostAttribute } = select( 'core/editor' );
const metas: { [ key: string ]: T } = getEditedPostAttribute( 'meta' ) || {};
return metas[ key ];
}, [] );
const { editPost } = useDispatch( 'core/editor' );
const setMeta = useCallback( ( value ) => {
editPost( {
meta: { [ key ]: value },
} );
}, [] );
return [ meta, setMeta ];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment