Last active
September 1, 2020 03:28
-
-
Save torounit/658fc871940c89ce0ea194392ab5ef2e to your computer and use it in GitHub Desktop.
useState 風味に WordPressのカスタムフィールドを扱うやつ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ]; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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