Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Can Not Read Properties of Undefined Reading Map in React JS

Today we are going to discuss a very common and frequent error in React JS which is “Can Not Read Properties of Undefined Reading Map in React JS”. This error you will face when you try to use the map() method, and this is possible that you can face this error since the map() method’s usage is high.

Now let’s see a very common and simple code to illustrate the problem, and we will see the solution for this problem.

Can Not Read Properties of Undefined Reading Map in React JS: Problem

import React, {useState, useEffect} from "react";
import "./App.css";

function App() {
  const [todo, setTodo] = useState();
  
  useEffect(()=>{
    getdata();
  })

  const getdata = async () => {
    const Response = await fetch('https://jsonplaceholder.typicode.com/todos/')
    .then((response) => response.json());
    setTodo(Response);
  }

  return (
    <div className="App">
      {todo.map( (record) =>(
        <div key={record.id}>
          {record.title}<br/><br/>
        </div>
      )
      )}
    </div>
  );
}

export default App;

Okay, now we have added a very simple code, as you can see we have very straightforward code. Here, we are fetching an API, and we are setting the response inside the state hook. Then we apply the map() method on this todo state, where we are fetching the title from this API. As you can see, the whole code looks errorless code, but if you try to run this code we won’t get the output.

And if we inspect the page to see the console, then the real problem will appear, which says “Can Not Read Properties of Undefined Reading Map”. A very huge-looking problem, right? but believe me, this error occurred due to a very simple mistake.

Can Not Read Properties of Undefined Reading Map

Can Not Read Properties of Undefined Reading Map in React JS: Solution

import React, {useState, useEffect} from "react";
import "./App.css";

function App() {
  const [todo, setTodo] = useState();
  
  useEffect(()=>{
    getdata();
  })

  const getdata = async () => {
    const Response = await fetch('https://jsonplaceholder.typicode.com/todos/')
    .then((response) => response.json());
    setTodo(Response);
  }

  return (
    <div className="App">
      {todo && todo.map( (record) =>(
        <div key={record.id}>
          {record.title}<br/><br/>
        </div>
      )
      )}
    </div>
  );
}

export default App;

Did we copy and paste the problem code again? looks pretty similar, right? But let me tell you that we have sorted the problem. You can see in the above code, we did a little modification before mapping todo, we are checking the todo state and if it is not empty then we will apply the map() method to it.

The question is why this error has occurred. so the simple answer is we didn’t check todo before applying map() on it. Here todo state is initially empty, or you can say null, so if we directly apply the map() method then map() won’t be able to find the title property.

Another question is raised we have called this API in the use effect () hook which allows us to do some work after the DOM gets painted so why todo state not updated? The reason this happens is that the API call is asynchronous, it doesn’t populate the state immediately, so the render happens first and tries to read the title property from the initial todo state which is null.

Can Not Read Properties of Undefined Reading Map

You may also like:

Reactjs Guru
Reactjs Guru

Welcome to React Guru, your ultimate destination for all things React.js! Whether you're a beginner taking your first steps or an experienced developer seeking advanced insights.

React tips & tutorials delivered to your inbox

Don't miss out on the latest insights, tutorials, and updates from the world of ReactJs! Our newsletter delivers valuable content directly to your inbox, keeping you informed and inspired.

9 Comments

  1. Actually i am new to react-js, while playing around some coding questions i was getting error of cannot read properties of map(“cities”).Below sending the entire code please look into it and revert me back with the solution. I am glad if someone could find solution. Thanks in Advance.

    import React, { useState } from ‘react’;
    import ‘./style.css’;

    const countries = [
    { name: ‘India’, countryCode: ‘IN’, cities: [“Delhi”, “Mumbai”] },
    { name: ‘Pakistan’, countryCode: ‘PAK’, cities: [‘Karachi’, ‘Lahore’] },
    { name: ‘America’, countryCode: ‘USA’, cities: [“Texas”, “Utah”] },
    ];
    export default function App() {
    const [country, setCountry] = useState([]);
    //Handler
    const changeHandler = (e) => {
    setCountry(e.target.value);

    };

    return (

    {/* 1 st drop down*/}

    {countries.map((item, index) => {
    return {item.name};
    })}

    {
    countries[country].cities.map((item,index)=>{
    return {item.cities};
    })
    }

    );
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents