In this how-to guide, we will be covering how you can access data from third-party services to hydrate your blocks.
Sometimes we need our blocks to consume third-party data, such as a blog API. In this how-to, we will see how to achieve just that.
We will be consuming data from https://jsonplaceholder.typicode.com/posts.
Open up your block's code and find getDataProps.js. It should look like this:
export const getDataProps = (utils, props) => Promise.resolve()
export const getDataProps = (utils, props) => {
return utils.client
.request('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.catch(e => [])
}
The request function is exactly like the fetch function, and works both in the server and on the client. You don't have to care about importing the right version of the function depending on which environment you are in.
From your render function located in src/Block.js, you will have the data available:
function StarterBlock(props) {
const posts = props.data;
...
}