Home > OS >  cannot read undefined error while changing object property inside an array of state hook
cannot read undefined error while changing object property inside an array of state hook

Time:11-01

i am making a todo list, and here is my two components:

ToDo.js :

import React, { useState } from 'react'
import AddNew from './Addnew';
import ToDoList from './ToDoList';

function Todo() {

    const[toDoList, setToDoList] = useState([]);

    function addNew(addText, date){
        console.log(addText);
        console.log(date);
        const obj = {
            text : addText,
            expiry : date,
            completed : false
        }
        const newToDo = [...toDoList, obj];
        setToDoList(newToDo); 

        console.log(toDoList);
    }

    function handleCheck(index){
        const newToDOs = [...toDoList, {}];
        console.log(index);
        console.log(toDoList);
        console.log(newToDOs);
        if(toDoList[index].completed==false){
            newToDOs[index].completed = false;
        }
        else {
            newToDOs[index].completed = true;
        }
        setToDoList(newToDOs);
    }


    return ( 
        <>
            <h1>To Do List</h1>
            <AddNew addNew={addNew}/>
            <ul className="list-group">
            <ToDoList list={toDoList} handleCheck={handleCheck} />
            </ul>
        </>
     );
}

export default Todo;

**ToDoList.js: **

import React from "react";

function ToDoList(props) {
  return (
    <>
        {props.list.length==0? <h3>To Do List is Empty</h3> : null}
      {props.list.map((element, index) => {
        return (
          <>
            <li className={element.completed? "list-group-item yes-comp" : "list-group-item no-comp" } >
            <span className="badge text-bg-info">{index   1}</span> &ensp; 
            <input type="checkbox" defaultChecked={element.completed} onChange={()=>{props.handleCheck({index})}} /> &ensp; 
            {element.text}  
            <span className="badge text-bg-light">{element.expiry.toString().slice(4,15)}</span>
            </li>
          </>
        );
      })}
    </>
  );
}

export default ToDoList;

now i am getting an error while checking and unchecking the checkbox in list of todos.. i am getting error

        if(**toDoList[index]**.completed==false){
            newToDOs[index].completed = false;
        }

right here in my ToDo.js the error is :

Todo.js:28 Uncaught TypeError: Cannot read properties of undefined (reading 'completed')
    at Object.handleCheck (Todo.js:28:1)
    at onChange (ToDoList.js:12:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:416

something is wrong an i cannot read completed property of my array of objects, and at first i tried to put newToDos inseted of toDoList in my if condition, but still that also dont work!!

CodePudding user response:

The error lies when you trigger handleCheck function. onChange={()=>{props.handleCheck({index})}}

here you are sending the index as inside a object.

So, when you try to access an array like this newToDOs[index].completed = false; you are not giving the actual index here. It becomes something like this newToDOs[{index: 0}] and that's why it throws an error.

Changing your trigger function to something like this onChange={() => props.handleCheck(index)} will work!

  • Related