I want to display user object's data on the page. Initially, I have
set the cats value to be an empty array using the useState which
you can see below.
useEffect(() => {
fetchItems();
}, []);
const [cats, setcats] = useState([]);
const fetchItems = async () => {
const data = await fetch("https://cat-fact.herokuapp.com/facts/");
const cats = await data.json();
setcats(cats.all);
};
Below is my render function.
<div>
<h1>Shop Page</h1>
<hr />
{cats.map((cat) => (
<div key={cat._id}>
<strong>Id: </strong>{" "}
<Link to={`/Shop/${cat._id}`} style={linkstyle}>
{cat._id}
</Link>
<br />
<strong>Text: </strong> {cat.text}
<br />
<strong>Upvotes: </strong> {cat.upvotes}
<strong>UserName: </strong>
{cat.user.name.first}
{/* Above line is not working */}
<p>{JSON.stringify(cat.user)}</p>
{/* Above line actually prints the complete data in a cat objects's data including first name and last name */}
<hr />
</div>
))}
</div>
I am getting the following error.
TypeError: Cannot read property 'name' of undefined
(anonymous function)
E:/online study/learn_react/react-router/src/Shop.js:38
35 | <br />
36 | <strong>Upvotes: </strong> {cat.upvotes}
37 | <hr />
> 38 | <strong>UserName: </strong>
| ^ 39 | {cat.user.name.first}
40 | {/* Above line is not working */}
41 | <p>{JSON.stringify(cat.user)}</p>
However JSON.stringify(cat.user) seems to work fine and display the
info in string format on the page.
https://cat-fact.herokuapp.com/facts/ response is the following.
{
"all": [
{
"_id": "58e009550aac31001185ed12",
"text": "The oldest cat video on YouTube dates back to 1894.",
"type": "cat",
"user": {
"_id": "58e007480aac31001185ecef",
"name": {
"first": "Kasimir",
"last": "Schulz"
}
},
"upvotes": 6,
"userUpvoted": null
},
{
"_id": "58e008340aac31001185ecfb",
"text": "Cats sleep 70% of their lives.",
"type": "cat",
"user": {
"_id": "58e007480aac31001185ecef",
"name": {
"first": "Kasimir",
"last": "Schulz"
}
},
]
}
I cannot understand what is the error I am making or the point I am overlooking. Please help me with this.
Thanks in Advance.
Attached are some screenshots for the reference.
[1]: https://i.sstatic.net/rSNIn.png [2]: https://i.sstatic.net/EMVS1.png [3]: https://i.sstatic.net/lk05x.png
Edit
I have found the solution from the answers given by the community. My code was correct but the user object seems to be missing in one of the responses which I didn't notice and also didn't filter out bad responses, which led to this error.
userproperty, so you'll need to use guards or optional chaining.