0

I'm building a featured posts block. I'd like to have a 1:1 preview of the rendered front-end in my editor, so that the experience isn't disconnected.

I have my basic block setup, attributes are correctly passed up/down from render.php to edit.js, and so on. Unfortunately, I can't find any documentation that would tell me:

  • Where it's best to fetch this data, and how - I'd assume in the edit.js file, which executed on a certain event, but should I use a query, an effect? I need to fetch the data before I render this thing - is a check enough? And so on.
  • If there is an automated way to fetch it already, and -
  • If it's officially supported.
  • How to not duplicate calls. For example, it would be nice if I just had a function I could call both on the front-end (through a REST endpoint, I guess?) and on the back-end, so that I don't have to duplicate logic.

I'm aware you could quite literally just write a fetch, but perhaps I missed something about this standard, because the "Gunteberg Block Handbook" didn't really mention it.

In essence, is there a standardized way of fetching data for Blocks, and if not, what's a good approach?

1 Answer 1

1

After reading through a lot of documentation/discussion, I found that the "official" way of requesting data for a block is useSelect. In my case, the answer would be:

const posts = useSelect(select => {
    return select("core").getEntityRecords("postType", "post", {
        per_page: 3,
        sticky: true
    });
});

Your Answer

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

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