1
votes

I am tying to fetch data to populate a select in a react gutenberg block. The code below gives me the posts from Wordpress. But I would like to filter these posts on a custom post type 'df_form'. How would I do that?

/**
 * Loading Posts
 */
getOptions() {
    let posts = new wp.api.collections.Posts();

    return ( posts).fetch().then( ( posts ) => {
        if( posts && 0 !== this.state.selectedPost ) {
            // If we have a selected Post, find that post and add it.
            const post = posts.find( ( item ) => { return item.id == this.state.selectedPost } );
            // This is the same as { post: post, posts: posts }
            this.setState( { post, posts } );
        } else {
            this.setState({ posts });
        }
    });

I tried this so far, but it didn't work:

let posts = wp.data.select('core').getEntityRecords('postType', 'df_form', { per_page: -1 });
1
Unrelated to your issue but per_page: -1 won't work as you expect: WordPress will only return up to 100 items per call (see developer.wordpress.org/rest-api/using-the-rest-api/pagination for more details.)cabrerahector

1 Answers

1
votes

When retrieving from the data store because some of the data is being loaded async, you need to wait until the application state is fully loaded. Esp. your circumstance where you are calling for data that relies on the REST API. You may want to think about Higher Order Components, specifically withSelect or useSelect.

getOptions = withSelect( (select) => { 
    return select('core').getEntityRecords('postType', 'df_form', { per_page: -1 });
} )

Here is the documentation for working with async data: https://developer.wordpress.org/block-editor/packages/packages-data/#api

Also, Have you tried using Gutenberg's api-fetch package?

apiFetch( { path: '/wp/v2/df_form' } ).then( posts => {
    console.log( posts );
} );

Here is the documentation: https://developer.wordpress.org/block-editor/packages/packages-api-fetch/