Created
June 25, 2021 20:58
-
-
Save chrisvanpatten/4a96fa904774b87c43a7c88953c2c85e to your computer and use it in GitHub Desktop.
React hook to retrieve the schema data for a set of meta keys in a WordPress post API request. Ideal for integrating libraries like React JSON Schema Form into a Gutenberg experience.
This file contains hidden or 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 apiFetch from '@wordpress/api-fetch'; | |
import { useSelect } from '@wordpress/data'; | |
import { useEffect, useState } from '@wordpress/element'; | |
import { getPath } from '@wordpress/url'; | |
import { pick } from 'lodash'; | |
function useMetaSchema( metaKeys ) { | |
const { _links } = useSelect( ( select ) => { | |
return select( 'core/editor' ).getCurrentPost(); | |
} ); | |
const [ schema, setSchema ] = useState( {} ); | |
const { self = [] } = _links; | |
if ( self.length < 1 ) { | |
return {}; | |
} | |
const path = getPath( self[ 0 ].href ).split( '/wp-json/' ).pop(); | |
useEffect( () => { | |
apiFetch( { | |
path, | |
method: 'OPTIONS', | |
} ).then( ( res ) => { | |
const metaSchema = res?.schema ?? {}; | |
const meta = metaSchema?.properties?.meta?.properties ?? {}; | |
metaSchema.properties = pick( meta, metaKeys ); | |
delete metaSchema.title; | |
setSchema( metaSchema ); | |
} ); | |
}, [ path ] ); | |
return { | |
schema, | |
}; | |
} | |
export default useMetaSchema; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: