Get data from external APIs
Sometimes you need to fetch data from external sources and render it inside bricks.
For instance, when creating a headless commerce system, some product data might come from the headless platform, while other parts of the product details page are visually edited by the marketing team. This approach is also useful when dealing with legacy APIs containing product data sheets.
In React Bricks, you can fetch external data at two levels:
- Within each brick that requires external data
- At the page level, defined for each pageType
Fetch external data in a brick
This is the most straightforward method, as each brick directly fetches the data it needs.
To fetch and use data from external APIs in a brick, define a getExternalData
function in the brick’s schema. This async function returns a promise that resolves to an object, which is then merged with the brick’s props.
For more details, see the schema’s Connect external APIs documentation.
Fetch external data in pages
If multiple bricks need to access the same external data, it may be more efficient to fetch this data at the page level and then allow each brick to use the relevant portion of the data.
In this scenario, define getExternalData
on the pageType
. For bricks that need to access this data, add a mapExternalDataToProps
function to their schema. This function maps the external data object on the page to an object that’s merged with the brick’s props.
For more information, refer to the Page Types documentation.