0

I'm working with the latest Gutenberg and WP and until last week, the code below worked as expected.

const postSelections = [];

const allPosts = wp.apiFetch({path: "/wp/v2/featured-post"}).then(fps => {
    postSelections.push({label: "Select a Post", value: 0});
    $.each( fps, function( key, val ) {
        postSelections.push({label: val.title.rendered, value: val.id});
    });
    return postSelections;
});

All of a sudden I'm getting wp.apiFetch is not a function errors.

Anyone have any idea why??

5
  • It looks like you are not adding the wp-api-fetch dependency in your script.
    – Alvaro
    Nov 28, 2018 at 19:37
  • I'm loading that through the PHP end: wp_register_script( 'featured-post-block-block-editor', plugins_url( $index_js, FILE ), array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-api', ), filemtime( "$dir/$index_js" ) ); Nov 28, 2018 at 20:18
  • Add also 'wp-api-fetch' and it should not throw the error.
    – Alvaro
    Nov 28, 2018 at 20:24
  • Winner winner, chicken dinner! Submit it as an answer if you want credit. The change from wp-api to wp-api-fetch worked. Odd though because up until version Gutenberg 4.4 wp-api alone worked. Nov 28, 2018 at 20:32
  • Things have been changing much last months in Gutenberg, it was a bit difficult sometimes to follow up, but it is already in RC. My suggestion is to check the code repository rather than the documentation, at least for the moment, until code is in official final stage and documentation gets fully updated.
    – Alvaro
    Nov 28, 2018 at 20:43

1 Answer 1

3

as @Alvero pointed out in the comments, instead of just supplying wp-api in the block registration, you now need to specify wp-api-fetch.

$index_js = 'sample-post/index.js';
wp_register_script(
    'sample-post-block-block-editor',
    plugins_url( $index_js, __FILE__ ),
    array(
        'wp-blocks',
        'wp-i18n',
        'wp-element',
        'wp-api-fetch',
    ),
    filemtime( "$dir/$index_js" )
);

Then within your block, you call it using the wp.apiFetch function:

var registerBlockType = wp.blocks.registerBlockType,
    el = wp.element.createElement,
    __ = wp.i18n.__,
    apiFetch = wp.apiFetch;

const postSelections = [];

const allPosts = apiFetch({path: "/wp/v2/featured-post"}).then(fps => {
    postSelections.push({label: "Select a Post", value: 0});
    $.each( fps, function( key, val ) {
        postSelections.push({label: val.title.rendered, value: val.id});
    });
    return postSelections;
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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