1

I'm developing a plugin for the new Gutenberg editor and I need to retrieve data from two REST API endpoints:

registerBlockType( 'my/block', {
    title: __( 'My Block' ),
    icon: 'email',
    category: 'common',
    attributes: {
        menu: {
            type: 'string',
            default: '0',
        },
    },

    edit: withAPIData( ( props ) => {
        return {
            menus: '/menus/v1/menus', // custom endpoint 1
            menu_selected: `/menus/v1/menus/${ props.attributes.menu }` // custom endpoint 2
        };
    } ) ( ( props ) => {
        const attributes = props.attributes;
        const menus = props.menus.data;
        const menu_selected = props.menu_selected.data;

        const setMenu = value => {
            props.setAttributes( { menu: value } );
        };

        if ( ! menus ) {
            return 'loading !';
        }

        if ( ! menu_sel ) {
            return 'loading !';
        }

        if ( menu_sel === '0' ) {
            return 'No menu selected';
        }

        return (
            ... omitted code for clarity ...  
        );
    }
} );

My question is, is this the correct way to do it? I'm asking this because right now I'm getting a permanent "loading !" message instead of the data from both endpoints. I tried to do the loading check with just one conditional too with no success:

if ( ( ! menus ) || ( ! menu_sel ) ) {
    return 'loading !';
}

Any hints?

Thanks!

  • Probably not but see github.com/WordPress/gutenberg/tree/master/components/… keep in mind that Gutenberg is super new and so you're much more likely to get good answers over at the GB project, and, answers here may not apply after a little time due to the in flux nature of GB – Tom J Nowell May 1 '18 at 20:34
  • However, it could be that you're trying to put too much in the 1 component, and need to break it apart so that you can use withAPIData twice rather than once – Tom J Nowell May 1 '18 at 20:37
  • The source code suggests you might be able to make multiple requests but provides no examples or docs, you'll need to open an issue to get it documented, it might be that it doesn't list the proper way to do it because nobody has decided what the proper way should be – Tom J Nowell May 1 '18 at 20:39

Your Answer

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

Browse other questions tagged or ask your own question.