Error – TypeError: Cannot read property ‘map’ of undefined

Often while coding, there are instances when we tend to face challenges in the form of errors. I have been through this time a lot. In ReactJS, I have encountered this error multiple times which says,

TypeError: Cannot read property ‘map’ of undefined

Mostly while using API Fetch in my App this error pops up. Why?

I searched the internet and found the solution to this problem. Whenever we are trying to use Fetch, we need to see if the data in the API is an object or an array. For example, below, data is an array. While in the case of this Random User API here – https://randomuser.me/api/?results=1, data is an object with results as the name.

API used here – https://api.github.com/users

[
  {
    "login": "mojombo",
    "id": 1,
    "node_id": "MDQ6VXNlcjE=",
    "avatar_url": "https://avatars0.githubusercontent.com/u/1?v=4",
    "gravatar_id": "",
    "url": "https://api.github.com/users/mojombo",
    "html_url": "https://github.com/mojombo",
    "followers_url": "https://api.github.com/users/mojombo/followers",
    "following_url": "https://api.github.com/users/mojombo/following{/other_user}",
    "gists_url": "https://api.github.com/users/mojombo/gists{/gist_id}",
    "starred_url": "https://api.github.com/users/mojombo/starred{/owner}{/repo}",
    "subscriptions_url": "https://api.github.com/users/mojombo/subscriptions",
    "organizations_url": "https://api.github.com/users/mojombo/orgs",
    "repos_url": "https://api.github.com/users/mojombo/repos",
    "events_url": "https://api.github.com/users/mojombo/events{/privacy}",
    "received_events_url": "https://api.github.com/users/mojombo/received_events",
    "type": "User",
    "site_admin": false
  },...
]

Here we are fetching Users which is an array, so we have to initialize users with an empty array in our useState hook

const GitUsers = () => {
  const [users, setUsers] = useState([]); //Initialize as an empty array
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

Now, store the User details from API in setUsers

useEffect(() => {
    fetch("https://api.github.com/users")
      .then((response) => response.json())
      .then(
        (data) => {
          setUsers(data); //User details from API stored in setUsers
          setLoading(true);
        },
        (error) => {
          setLoading(true);
          setError(error);
        }
      );
  }, []);

Finally we used Map to display the data on our page. using Map, we looped through User array and displayed each item in return

return (
      <div className="card-columns" id="card-column">
        {users.map((user) => (
          <div key={user.id}>
            <div className="card" id="userpage">
              <img
                className="card-img-top"
                id="cardimage"
                src={user.avatar_url}
                alt="user1"
              />
              <div className="card-body">
                <h5 className="card-title">{user.login}</h5>
                <p className="card-text">{user.url}</p>
                <a href={user.repos_url} className="btn btn-primary">
                  See Repos
                </a>
              </div>
            </div>
          </div>
        ))}
      </div>
    );

Full code is here –

import React, { useState, useEffect } from "react";
import "./GitUsers.scss";

const GitUsers = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch("https://api.github.com/users")
      .then((response) => response.json())
      .then(
        (data) => {
          setUsers(data);
          setLoading(true);
        },
        (error) => {
          setLoading(true);
          setError(error);
        }
      );
  }, []);

  if (error) {
    return <h5>There was some error, try again</h5>;
  } else if (!loading) {
    return <p>loading...please wait</p>;
  } else {

    return (
      <div className="card-columns" id="card-column">
        {users.map((user) => (
          <div key={user.id}>
            <div className="card" id="userpage">
              <img
                className="card-img-top"
                id="cardimage"
                src={user.avatar_url}
                alt="user1"
              />
              <div className="card-body">
                <h5 className="card-title">{user.login}</h5>
                <p className="card-text">{user.url}</p>
                <a href={user.repos_url} className="btn btn-primary">
                  See Repos
                </a>
              </div>
            </div>
          </div>
        ))}
      </div>
    );
  }
};

export default GitUsers;

Thanks to Rahman Fadhil for this nice post – https://rahmanfadhil.com/fetch-data-with-react-hooks/?utm_source=jayeshposts.wordpress.com

Keep Coding!

Jayesh

With ReactJS, Jayesh

ReactJS has become a special part of my everyday life. I dream about it and when I wake up in the morning, I am still thinking of building something with it. Web Apps are my favorite toys.

I will keep sharing my journey through ReactJS everyday in pieces. If the posts in this blog helps you in some kind, I would be proud.

Thank you for being a part of this road, it never gonna end.

Baby, you a song,
You make me wanna roll my windows down and cruise…

Cruise – Florida Georgia Line, 2012

Kudos,

Jayesh