I have created a rather complex Gutenebrg Block
I have hardcoded the Post / Project IDs and I am now struggling how to implement the update function. I use two different API Routes and want to give the user the possibilty to change the Block Content via typing in the ID in a field.
Passing an attribute into :
withSelect(select => {
return {
posts: select('core').getEntityRecords('/wp/v2', 'projects', {include: 2962}),
posts1: select('core').getEntityRecords('/wp/v2', 'posts', {include: 3432})
};
})
Most of the code below… It was rather tricky for me as a Gutenberg rookie...
/**
* Block dependencies
*/
import './style.scss';
/**
* Internal block libraries
*/
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { Spinner } = wp.components;
const { withSelect, useSelect } = wp.data;
const {
InspectorControls,
RichText,
MediaUpload,
URLInputButton
} = wp.blockEditor;
var dispatch = wp.data.dispatch;
dispatch( 'core' ).addEntities( [
{
name: 'projects', // route name
kind: '/wp/v2', // namespace
baseURL: '/wp/v2/projects/' // API path without /wp-json
},
{
name: 'posts', // route name
kind: '/wp/v2', // namespace
baseURL: '/wp/v2/posts/' // API path without /wp-json
}
]);
registerBlockType(
'jsforwpblocks/dynamic',
{
title: __( 'Example - Dynamic Block', 'jsforwpblocks'),
description: __( 'A look at how to build a basic dynamic block.', 'jsforwpblocks'),
icon:'shield',
category: 'widgets',
attributes: {
projektID: {
type: 'string',
},
},
edit:
withSelect( select => {
return {
posts: select( 'core' ).getEntityRecords( '/wp/v2', 'projects',{include: 2962}),
posts1: select( 'core' ).getEntityRecords( '/wp/v2', 'posts',{include: 3432})
};
} )
( ( { props, posts, posts1, className, isSelected, setAttributes,attributes } ) => {
if ( ! posts ) {
return (
<p className={className} >
<Spinner />
{ __( 'Loading Posts', 'jsforwpblocks' ) }
</p>
);
}
if ( 0 === posts.length ) {
return <p>{ __( 'No Posts', 'jsforwpblocks' ) }</p>;
}
function changeprojektid(projektID) {
// using some nice js features instead of typing
// { heading: heading }
setAttributes({ projektID });
withSelect( select => {
let query = 'include: 2962'
return {
posts: select( 'core' ).getEntityRecords( '/wp/v2', 'projects', {include: 2962})
};
} )
}
return (
<div>
<div className="copy">
<RichText
className="heading"
tagName="h2"
placeholder="Enter your ID"
value={attributes.projektID}
onChange={changeprojektid}
/>
</div>
<ul className={ className }>
{ posts.map( post => {
return (
<li>
<a className={ className } href={ post.link }>
{ post.title.rendered }
<img src={ post.projimage1.guid } />
</a>
</li>
);
}) }
</ul>
<ul className={ className }>
{ posts1.map( post => {
return (
<li>
<a className={ className } href={ post.link }>
{ post.title.rendered }
</a>
</li>
);
}) }
</ul>
</div>
);
} )
// end withAPIData
, // end edit