Home > database >  TypeError: Cannot read properties of undefined(reading 'map') in react.js
TypeError: Cannot read properties of undefined(reading 'map') in react.js

Time:10-29

I don't understand why I am getting this error: TypeError: Cannot read properties of undefined(reading 'map') in react.js

Could someone explain to me why?

import React, { useState, useEffect } from 'react';


const UsersList = () => {
  const LIST_URL = "https://jsonplaceholder.typicode.com/users "
  const [users, setUsers] = useState([])

  useEffect(() => {
    fetch(LIST_URL)
      .then(res => res.json())
      .then(json => setUsers(json.results))
  }, [])

  return (
    <>
      <header>      
        <h1>My contact list</h1>
      </header>
      <section> 
        <ul>
          {users.map(user => (
            <li key={user.id}>{user.name}</li>
          ))}         
        </ul>
      </section>
    </>
  )
}

export default UsersList

CodePudding user response:

There is no property as json.results, you should assign the json to the state as

setUsers(json)

Codesandbox Demo

  useEffect(() => {
    fetch(LIST_URL)
      .then((res) => res.json())
      .then((json) => setUsers(json));
  }, []);

CodePudding user response:

you must check if users is not array empty you can write like this:

return (
    <>
      <header>      
        <h1>My contact list</h1>
      </header>
      <section> 
        <ul>
          {users.length > 0 && users.map(user => (
            <li key={user.id}>{user.name}</li>
          ))}         
        </ul>
      </section>
    </>
  )
  • Related