I need to map over an array of novels a user has saved in order to render info cards on each novel. Each time I try, the page fails to load and I get "TypeError: Cannot read properties of null (reading 'name')--attempting to read the novel's name etc. The query works perfectly on the back end, and I'm able to console log all of the data in the browser, so I'm not sure why I'm getting "undefined."
I've found that I'm able to render data from the user level, but not the "novels" sub-level. So I think the problem may have something to do with the mapping?
Here is the query:
{
user {
_id
name
novels {
_id
name
author
rank
isComplete
}
}
}
And relevant code from the component:
if (data) {
user = data.user
console.log(user.novels)
}
return (
<>
<div className="row">
{user ? (
<>
<h2>Your Novels:</h2>
{user.novels.map((novel) => (
<div
key={novel._id}
className="col-sm-12 col-md-2 col-lg-2 card">
<p> {novel.name}
< br />
<span className="card-subheader" >by</span> {novel.author}
< br />
<span className="card-subheader">Rank:</span> {novel.rank}
< br />
<span key={novel.isComplete}>{novel.isComplete}</span>
</p>
</div>
))}
) : null}
</div>
</>
);
}
So basically, it's able to render user.name for example, but not user.novel.name
Any help would be SO appreciated! (And this is my first post, so apologies in advance if I'm missing anything)
CodePudding user response:
It seems it is not fault of your code in the frontend. You should check user in console. It may user.novels contain an empty objects caused an error reading novel.name, like this:
{
user: {
_id: ...
name: ...
novels: [
null or {}, // novel is null so reading novel.name cause the error.
{
_id: ...
name: ...
author: ...
rank: ...
isComplete: ...
}
],
...
}
}
However you can check this in frontend, but technically these empty objects should not be in your response from backend and should fix them.
