Provide main entity metadata in drupalSettings and code component utils package
[#3565754]
This MR:
- Introduces a new key called
mainEntityindrupalSettingsthat provides the entity's UUID, entityTypeId, and bundle. - Expand function
getPageData()fromdrupal-utilswhich returns the abovemainEntity - main entity can either be:
-
mainEntity: null// on non-entity route (inside code editor, home page, /user/login) -
mainEntity: {bundle: 'article', entityTypeId: 'node', uuid: '8d32b7ea-9c19-4cd3-a008-9a374ba6e876'}(on an entity route)
-
Example usage:
On article 2 and the code component code filters out the current entity (article 2) from the related article using drupal-jsonapi-paramsand filter by the current entity uuid.
import { getPageData } from 'drupal-canvas';
import { JsonApiClient } from 'drupal-canvas';
import { DrupalJsonApiParams } from 'drupal-jsonapi-params';
import useSWR from 'swr'
const client = new JsonApiClient();
function RelatedArticles({ mainEntity }) {
const { bundle, entityTypeId, uuid } = mainEntity;
const { data, error, isLoading } = useSWR(
[
'node--article',
{
queryString: new DrupalJsonApiParams()
.addFilter('id', uuid, '<>') // Exclude current article by uuid.
.getQueryString(),
},
],
([type, options]) => client.getCollection(type, options),
);
return (...);
}
// Wrapper component to check for mainEntity existence and type before calling a hook since
// hooks cannot be called conditionally (React rules of hooks).
function RelatedArticlesWrapper() {
const { mainEntity } = getPageData();
// Return early if there is no mainEntity, or it is not an article node.
if (
!mainEntity ||
mainEntity.entityTypeId !== 'node' ||
mainEntity.bundle !== 'article'
) {
return null;
}
return <RelatedArticles mainEntity={mainEntity} />;
}
export default RelatedArticlesWrapper;
Edited by Harumi Jang
