var is undefined in a Gutenberg block
-
20-03-2021 - |
Question
I'm fiddling with Gutenberg right now and I'm stuck trying to build a dynamic block. This is the code I'm using (some code is omitted for clarity):
registerBlockType( 'my/block', {
title: __( 'My Block' ),
icon: 'email',
category: 'common',
attributes: {
menu: {
type: 'string',
default: '',
},
},
edit: withAPIData( ( props ) => {
return {
menu_selected: `/menus/v1/menus/${ props.attributes.menu }` // custom endpoint
};
} ) ( ( props ) => {
const attributes = props.attributes;
const menu_selected = props.menu_selected.data;
const setMenu = value => {
props.setAttributes( { menu: value } );
};
console.log( JSON.stringify( menu_selected ) );
const ar = menu_selected.map( ( item ) => {
return (
<li className="menu_item">
{ item.post_title }
</li>
);
} );
}
} );
console.log( JSON.stringify( menu_selected ) )
returns the following string:
[{"ID":3729,"post_title":"Item 1","post_type":"nav_menu_item"},
{"ID":3730,"post_title":"Item 2","post_type":"nav_menu_item"}]
But when I call map()
on the menu_selected
var I get a "menu_selected is undefined" error and I don't understand why.
Any ideas?
Thanks in advance
Solution
I think you have to pass in menu_selected
edit: withAPIData( ( props ) => {
return {
menu_selected: `/menus/v1/menus/${ props.attributes.menu }` // custom endpoint
};
} ) ( ( { menu_selected } ) => {
I was able to do a very similar thing like so:
edit: withAPIData( () => {
return {
posts: '/wp/v2/images?per_page=4&_embed'
};
} )( ( { posts, className } ) => {
if ( ! posts.data ) {
return "loading !";
}
if ( posts.data.length === 0 ) {
return "No posts";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange