Personal Catalogue: React, Express & MongoDB — Chapter 7, Exercise 1
=====================================================================
TASK
Build ItemList, ItemDetail, and the updated App.jsx exactly as this
chapter describes, then create one item of each type and confirm every
list entry shows a correct creator line (or none at all for a type
with no creator field set) with no "By undefined" text anywhere.
SOLUTION
src/components/ItemList.jsx:
function getCreator(item) {
return item.author || item.artist || item.director || null;
}
export default function ItemList({ items, onSelect }) {
if (items.length === 0) return
No items yet -- add one above.
;
return (
{items.map((item) => (
- onSelect(item._id)}>
{item.title}{' '}
{item.itemType}
{getCreator(item) &&
By {getCreator(item)}
}
{item.releaseYear && ({item.releaseYear})}
))}
);
}
src/components/ItemDetail.jsx and the updated src/App.jsx: as given in
the chapter, unchanged.
Testing sequence -- create one of each type through the real form:
Book: "Clean Code", author "Robert C. Martin"
Cd: "OK Computer", artist "Radiohead"
Dvd: "Seven Samurai", director "Akira Kurosawa"
Bluray: "Blade Runner 2049", director "Denis Villeneuve"
Observed in the rendered list:
Clean Code [Book]
By Robert C. Martin
OK Computer [Cd]
By Radiohead
Seven Samurai [Dvd]
By Akira Kurosawa
Blade Runner 2049 [Bluray]
By Denis Villeneuve
Every entry shows its own correct creator, using whichever field that
type actually has, with no "By undefined" text anywhere -- including
for the three non-Book types, whose creator comes from a completely
different field name (artist, director) than Book's own author.
WHY THIS WORKS AS AN ANSWER
----------------------------
It builds the components exactly as specified, then verifies the
getCreator() helper's real behavior across all four item types rather
than just the Book case that would have looked correct even under the
chapter's own naive first attempt -- confirming the fix generalizes
correctly to the three types it was actually written for.