There are multiple better ways to get a list of posts in a Gutenberg block, other than rendering serverside.
First is to use the Wrodpress wrapper around Redux and select posts exactly like in the Gutenberg Handbook:
edit: withSelect( function( select ) {
return {
posts: select( 'core' ).getEntityRecords( 'postType', 'post' )
};
} )( function( props ) {
if ( ! props.posts ) {
return "Loading...";
}
if ( props.posts.length === 0 ) {
return "No posts";
}
var className = props.className;
var post = props.posts[ 0 ];
return el(
'a',
{ className: className, href: post.link },
post.title.rendered
);
} ),
Notice how the edit function is composed with data from the Gutenberg store and it gets the posts array as a prop.
The second option is to simply use Axios to get the posts you need via the rest API:
/**
* Makes a get request to the desired post type and builds the query string based on an object.
*
* @param {string|boolean} restBase - rest base for the query.
* @param {object} args
* @returns {AxiosPromise<any>}
*/
export const getPosts = ({ restBase = false, ...args }) => {
const queryString = Object.keys(args).map(arg => `${arg}=${args[arg]}`).join('&');
return axios.get(`/wp-json/wp/v2/${restBase}? ${queryString}&_embed`);
};
This is a snippet from this great tutorial: https://github.com/bigbitecreative/gutenberg-postlist-demo
After the posts call is defined you may use componentDidMount to call it and then set the posts as the new Modal componenet state:
/**
* When the component mounts it calls this function.
* Fetches posts types, selected posts then makes first call for posts
*/
componentDidMount() {
this.setState({
loading: true,
});
api.getPostTypes()
.then(({ data = {} } = {}) => {
this.setState({
types: data
}
});
}
Also from Gutenberg Postlist demo but shortened for brevity.