简体   繁体   中英

TypeError: Cannot read properties of undefined (reading 'filter')

I am trying to create an event to delete elements on button click but get the error "TypeError: Cannot read properties of undefined (reading 'filter')"

const Todo = ({ text, todo, todos, setTodos }) => {
  const deleteHandler = () => {
    setTodos(todos.filter((el) => el.id !== todo.id));
  };

  return (
    <div className="todo">
      <li className="todo-item">{text}</li>
      <button className="complete-btn">
        <i className="fas fa-check"></i>
      </button>
      <button onClick={deleteHandler} className="trash-btn">
        <i className="fas fa-trash"></i>
      </button>
    </div>
  );
};

you have to check if element exists or not, i am hoping its array with id property, if its undefined , so no point in calling .fliter on it, it will surely throw error, call only when it have data, like this will fix the issue, i do this in my project too,

const deleteHandler = () =>{
   setTodos(todos && todos.filter((el) => el.id !== todo.id));
};

you can do this instead,

const deleteHandler = () =>{
   if(todos ){
      setTodos(todos.filter((el) => el.id !== todo.id));
   }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM