so basically I build a todo list app, using mern stack and whenever I am adding todo it gives me todo.map error.
I have a context from there it is importing some function to fetch!
Whenever someone adds a todo just add it and then call the fetchTodo function to update the todo, but on adding it gives me the error
import React, { useContext, useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import GigContext from '../../context/Gig/GigContext';
import TodoContext from '../../context/Todo/TodoContext';
import AddTodo from './AddTodo';
import { Link } from 'react-router-dom';
export default function Todo() {
const context = useContext(GigContext);
const Todocontext = useContext(TodoContext);
const [visiblity, setvisiblity] = useState(false);
const { fetchTodo, todo } = Todocontext;
const { getSingleGig, oneGig } = context;
const { id } = useParams();
useEffect(() => {
getSingleGig(id);
fetchTodo(id);
console.log(todo);
}, []);
return (
<>
<div className="p-6">
<Link to="/" className="cursor-pointer">
<i class="fa-solid fa-arrow-left mr-2"></i>Go back
</Link>
<h1 className="text-4xl font-bold mt-5 text-center">{oneGig.title}</h1>
<div className="flex justify-center flex-wrap mt-10 p-2 h-[100%] ">
{/* card */}
{!todo == [] &&
todo.map((e) => {
console.log(e);
return (
<div key={e._id} className="bg-gray-200 w-[80%] h-min p-5 rounded-lg mt-8">
<h4 className="text-start text-xl font-medium">{e.title}</h4>
</div>
);
})}
{/* add */}
</div>
<div className="w-[100%] flex justify-center sticky bottom-2 mb-2 mt-20">
<button
onClick={() => {
setvisiblity(true);
}}
className="w-[70%] h-20 bg-gray-100 rounded-md border-dashed border-black border-2 hover:bg-gray-200 transition-all text-xl">
Add <span className="fa-l fa-plus fa-xl ml-2"></span>
</button>
</div>
</div>
<AddTodo visiblity={visiblity} setvisiblity={setvisiblity} id={id} />
</>
);
}
2
Answers
Just change the condition
!todo == []
totodo.length
to check if the
todo
array is empty or not.!todo == []
checks for strict equality between the negation of todo and an empty array.but you know your endpoint may return an empty array.
think about it.
better is to initialize
todo
withundefined
and checktodo && <>..</>
so you are sure it is the first renderUse this simple condition