Skip to content

Instantly share code, notes, and snippets.

@youknowriad
Last active August 16, 2019 20:56
Show Gist options
  • Save youknowriad/a061b46fc7da8de41e0d9cc2beeb27b4 to your computer and use it in GitHub Desktop.
Save youknowriad/a061b46fc7da8de41e0d9cc2beeb27b4 to your computer and use it in GitHub Desktop.
EntityProviders
// Probably a file in core-data module
/**
* WordPress dependencies
*/
import { createContext, useContext } from '@wordpress/element';
import { useSelect, useDispatch } from '@wordpress/data';
const PostEntityContext = createContext( null );
const SiteEntityContext = createContext( null );
const entityContexts = {
post: PostEntityContext,
site: SiteEntityContext,
};
const entityKind = {
post: [ 'postType' ],
site: [ 'root' ],
};
export function EntityProvider( { entityId, type, children } ) {
const currentContext = entityContexts[ type ];
return (
<currentContext.Provider value={ entityId }>{ children }</currentContext.Provider>
);
}
export function useEntityProperty( type, propertyName ) {
const currentContext = entityContexts[ type ];
const entityId = useContext( currentContext );
const propertyValue = useSelect( ( select ) => {
return select( 'core' )
.getEditedEntityRecord( entityKind[ type ], type, entityId )
[ propertyName ];
}, [ entityId, propertyName ] );
const { editEntityRecord } = useDispatch( 'core' );
const onChange = ( value ) => editEntityRecord( entityKind[ type ], type, entityId, {
[ propertyName ]: value,
} );
return [ propertyValue, onChange ];
}
export default function PostContentEdit() {
const [ value, onChange ] = useEntityProperty( 'post', 'blocks' );
return (
<BlockEditorProvider
value={ blocks }
onChange={ onChange }
onInput={ onChange }
>
<BlockList />
</BlockEditorProvider>
);
}
export default function PostEdit( { attributes: { postId } } ) {
return (
<EntityProvider entityId={ postId } type="post">
<InnerBlocks />
</EntityProvider>
);
}
export default function PostTitleEdit() {
const [ value, onChange ] = useEntityProperty( 'post', 'title' );
return (
<RichText
value={ value }
onChange={ onChange }
tagName="h1"
placeholder={ __( 'Title' ) }
formattingControls={ [] }
/>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment