Cannot read properties of undefined (reading ‘_id’) TypeError: Cannot read properties of undefined (reading ‘_id’)
this is my App.js file
function App() {
const [todos, setTodos] = useState([]);
const [popupActive, setPopupActive] = useState(false);
const [newTodo, setNewTodo] = useState("");
useEffect(() => {
GetTodos();
}, []);
const GetTodos = () => {
fetch(api_base + '/todos')
.then(res => res.json())
.then(data => setTodos(data))
.catch((err) => console.error("Error: ", err));
}
const completeTodo = async id => {
const data = await fetch(api_base + '/todo/complete/' + id).then(res => res.json());
setTodos(todos => todos.map(todo => {
if (todo._id === data._id) {
todo.complete = data.complete;
}
return todo;
}));
}
const deleteTodo = async id => {
const data = await fetch(api_base + '/todo/delete/' + id, { method: "DELETE" }).then(res => res.json());
setTodos(todos => todos.filter(todo => todo._id !== data.result._id));
}
2
Answers
That is because the data must be getting undefined there, try to add a condition to check if data is present ,this is actually type error and you can fix this by checking if data and its properties are present continue with process this will prevent type errors
the function will trigger only if the data is present so you won’t get any undefined error, copy paste this and try.I hope it works!!
You should have check the
result
key insidedata
response. You can check the below code for result key validation