Map method is undefined in React

Asked

Viewed 128 times

2

I’m building an application in React and need to render a list of all users, called the API. Use the map to go through the users, but the browser returns the error:

TypeError: Cannot read property 'map' of undefined.

My comfort is like this:

<ul>
     {devs.map((dev) => (
            <li key={dev._id} className="dev-item">
              <header>
                <img src={dev.avatar_url} alt={dev.name}></img>
                <div className="user-info">
                  <strong>{dev.name}</strong>
                  <span>{dev.techs.join(', ')}</span>
                </div> 
              </header>
              <p>{dev.bio}</p>
              <a href={`https://github.com/${dev.github_username}`}>Acessar perfil</a>
            </li>
          ))}
 </ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

How to resolve the error?

  • Where does that come from supposed array devs? In fact it is not an React error. Probably devs is not being accessed correctly-currently, devs is undefined, and therefore the mistake.

  • You are doing the rocketseat week training and did not pay attention to the ball !!! kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk devs and as it was maybe you initialized wrong. Well put the whole function.

1 answer

3


According to the comments, the "Cannot read Property 'map' of Undefined" error occurs because the "map" applies to arrays, and "devs" must be null.

As one of the colleagues commented that this code is from Omnistack week, it was possible to identify the cause of the error. "devs" is part of the state of its component, when initialized, it is an empty array.

function App() {

  const [devs, setDevs] = useState([]);

  //Programação do componente

}

When loading the component, you should search the API

function App() {

  const [devs, setDevs] = useState([]);

  useEffect(() =>{
    async function loadDevs() {
      const response = await api.get('/devs');

      setDevs(response.data);
    }

    loadDevs()
  }, []);
  //Programação do componente

}

If the error persists, it may be a problem in the API query, you should do a test of this GET route to see if it is returning any users. You can test communication using Postman

Browser other questions tagged

You are not signed in. Login or sign up in order to post.