Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'map' of undefined in React

Tags:

I'm learning a react course online. When I try to display the list of items from an array using map to display in a child component , I keep getting "cannot read property map of undefined.

Error is thrown while fetching data from users

import React, { Component } from "react";
import ReactDOM from "react-dom";


let userList = [
  { name: "John", age: 24, place: "India" },
  { name: "Henry", age: 24, place: "India" },
  { name: "Ulrich", age: 24, place: "India" }
];

const AppChild = ({ name, age, place, Graduated }) => {
  return (
    <section>
      <p>name: {name}</p>
      <p>age: {age}</p>
      <p>place: {place}</p>
      {/* access the value via props */}
      <p>Graduated: {Graduated ? "yes!" : "no!"}</p>
    </section>
  );
};


export default class App extends Component {
    
  state = {
    userExists: true,
    isGraduated: true,
    loading: true,
  }; 


  toggleStatus = () => {
    this.setState(prevState => ({
      userExists: !prevState.userExists // value : false
    }));
  };

  render() {
    const { users } = this.props; 
    return (
      <div>
        <h2>Profile</h2>
        <h4>
          Profile Status is {this.state.userExists ? "Updated" : "Outdated"}
          <br />
          <button onClick={this.toggleStatus}>Check Status</button>
        </h4>
        {users.map(user => (
          
          <AppChild
            name={user.name}
            age={user.age}
            place={user.place}
            Graduated={this.state.isGraduated} // passing state to child component
          />
        ))}
      </div>
    );
  }
}

ReactDOM.render(<App users={userList} />, document.getElementById("root"));


like image 459
Akhil Suseelan Avatar asked Jul 20 '20 05:07

Akhil Suseelan


1 Answers

To figure out the problem, we follow the bouncing ball. From the error message, I guess that the problem occurs on the line

        {users.map(user => (

(You can confirm this from the stack trace given with the error message.)

The error tells you that users is undefined. So we look at the declaration for users:

    const { users } = this.props; 

Ok, so it is really this.props.users. So we look where this is passed in:

ReactDOM.render(<App users={userList} />, document.getElementById("root"));

Here you are passing the value of userList to a prop named users. However, in the code you show here, there is no variable named userList. This is as far as we can go with the information you have given. You need to find where this variable is declared and initialized to continue solving the problem.

like image 112
Code-Apprentice Avatar answered Sep 28 '22 09:09

Code-Apprentice