Uncaught TypeError: wp.apiFetch is not a function

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??

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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;
});


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x