0

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.

1
  • Your code is mostly fine, it's just that somewhere in the hundreds of response objects at least one is missing the user property, so you'll need to use guards or optional chaining. Commented Jul 29, 2020 at 16:43

2 Answers 2

1

The response from https://cat-fact.herokuapp.com/facts/ includes a cat that is missing the user property

{
  _id: "58e008450aac31001185ecfd", 
  text: "A cat was mayor of Talkeetna, Alaska, for 20 years…His name is Stubbs, and he died on July 23, 2017.", 
  type: "cat", 
  upvotes: 1, 
  userUpvoted: null
}

Either fix the data or e.g. filter it out:

setcats(cats.all.filter(c => c.user));
Sign up to request clarification or add additional context in comments.

Comments

0

A user property doesn't exist this Id: 58e008450aac31001185ecfd

you can try this : { cat.user && cat.user.name.first}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.