Skip to content

Commit

Permalink
catalog: fix EntitySwitch to render default case
Browse files Browse the repository at this point in the history
Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
  • Loading branch information
Rugvip committed Mar 15, 2022
1 parent 12693d5 commit d4afa7e
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/shy-seals-deny.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@backstage/plugin-catalog': patch
---

Fix for `EntitySwitch` not properly falling back to render the default entity page when the entity is missing.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@
*/

import { Entity } from '@backstage/catalog-model';
import { EntityProvider } from '@backstage/plugin-catalog-react';
import {
AsyncEntityProvider,
EntityProvider,
} from '@backstage/plugin-catalog-react';
import { render } from '@testing-library/react';
import React from 'react';
import { isKind } from './conditions';
Expand Down Expand Up @@ -76,6 +79,18 @@ describe('EntitySwitch', () => {
expect(rendered.queryByText('A')).not.toBeInTheDocument();
expect(rendered.queryByText('B')).not.toBeInTheDocument();
expect(rendered.queryByText('C')).toBeInTheDocument();

rendered.rerender(
<Wrapper>
<AsyncEntityProvider entity={undefined} loading={false}>
{content}
</AsyncEntityProvider>
</Wrapper>,
);

expect(rendered.queryByText('A')).not.toBeInTheDocument();
expect(rendered.queryByText('B')).not.toBeInTheDocument();
expect(rendered.queryByText('C')).toBeInTheDocument();
});

it('should switch child when filters switch', () => {
Expand Down
18 changes: 15 additions & 3 deletions plugins/catalog/src/components/EntitySwitch/EntitySwitch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export interface EntitySwitchProps {

/** @public */
export const EntitySwitch = (props: EntitySwitchProps) => {
const { entity } = useAsyncEntity();
const { entity, loading } = useAsyncEntity();
const apis = useApiHolder();
const results = useElementFilter(
props.children,
Expand All @@ -75,19 +75,31 @@ export const EntitySwitch = (props: EntitySwitchProps) => {
})
.getElements()
.flatMap<SwitchCaseResult>((element: ReactElement) => {
if (!entity) {
// Nothing is rendered while loading
if (loading) {
return [];
}

const { if: condition, children: elementsChildren } =
element.props as EntitySwitchCase;

// If the entity is missing or there is an error, render the default page
if (!entity) {
return [
{
if: condition === undefined,
children: elementsChildren,
},
];
}
return [
{
if: condition?.(entity, { apis }) ?? true,
children: elementsChildren,
},
];
}),
[apis, entity],
[apis, entity, loading],
);
const hasAsyncCases = results.some(
r => typeof r.if === 'object' && 'then' in r.if,
Expand Down

0 comments on commit d4afa7e

Please sign in to comment.