1

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

1
  • 1
    is that the full error? Bonus tip, you can remove the JSON.stringify and call console.log directly on the object/array and it'll appear in the console letting you expand and collapse, and even copy it into the clipboard. It's possible this is Babel/Webpack related
    – Tom J Nowell
    May 1, 2018 at 16:02

1 Answer 1

2

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";
      }
1
  • 1
    Thanks! Looking at your second snippet of code I realized that I forgot to check if the menu_selected var was already populated with data coming from the REST API endpoint.
    – leemon
    May 1, 2018 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.