All games don't have parent_platforms, causes crash

Sharing in case this helps anyone or if someone has a better fix.

I got a fatal error in the GameCard.tsx component after doing a search and then ordering by release date. It seems some games don’t have all information.

I did a search for “blood” and then order by release to cause the crash.
The first game in the list has no parent_platforms.

The error is Cannot read properties of undefined (reading ‘map’)

Here is how I fixed it.

In GameCard.tsx

{game.parent_platforms && (
  <PlatformIconList
    platforms={game.parent_platforms.map((p) => p.platform)}
  />
)}

Also I set it to optional in Game type

type Game = {
  id: number;
  name: string;
  background_image: string;
  parent_platforms?: { platform: Platform }[];
  metacritic: number;
  rating_top: number;
};

UPDATE:
This comes back to bite us in more than one place. Now in the new DefinitionItem component.

I just figured out there is no need for wrapping the component in a check like I did above. I left parent_platforms? optional in my Game type but then wherever I use it I use optional chaining. In the example above with optional chaining, it just won’t try to map the items so there won’t be any displayed. Maybe I missed it in the lesson but platforms being passed to PlatformIconList should be like this.

<PlatformIconList
    platforms={game.parent_platforms?.map((p) => p.platform)}
  />

Then in PlatformIconList.tsx make the Prop platforms? optional and then again in that component where we map over them, use optional chaining.

The same game works for DefinitionItem.tsx

In GameDetailPage.tsx

<DefinitionItem term="Platforms">
  {game.parent_platforms?.map(({ platform }) => (
    <Text key={platform.id}>{platform.name}</Text>
  ))}
</DefinitionItem>

I am wondering though if it is better to check that it is not null or undefined at the very beginning and just not render the next component at all rather than putting these ? marks all over the project. Especially in the case of the PlatformIconList where I am passing a possibly undefined array as an optional prop to then optionally map over it if it is not undefined.

So anyway, There are 2 ways to deal with it.