I am coding a task tracker when you can add and remove tasks. Each task have id value and when you add a new task the id will be the last one + 1. If I remove the whole tasks and then adding one the id will be NaN I would like to get some help :)
tasks -
const App = () => {
const [tasks, setTasks] = useState([
{
id: 1,
text: 'Taking react course',
day: 'Aug 29th at 9:00am ',
reminder: true,
},
{
id: 2,
text: 'Exersice at the gym',
day: 'Aug 29th at 1:00pm',
reminder: true,
},
]);
};
when Adding task -
const onAdd = (task) => {
const id = tasks[tasks.length - 1]?.id + 1; // Without this line I am getting undefined id error so thats why I putted that question mark over there.
const newTask = { id, ...task };
setTasks([...tasks, newTask]);
};
Presumably this could potentially resolve to null here:
tasks[tasks.length - 1]?.id
But you can provide a default value of 0 when that happens:
tasks[tasks.length - 1]?.id ?? 0
So this should always at least resolve to a valid number:
const id = (tasks[tasks.length - 1]?.id ?? 0) + 1;
You can conditionally assign a value to id as follows:
we will check if tasks array is empty or not if its empty we will set id=1 else we will go with regular logic
const onAdd = (task) => {
const id = tasks.length <= 0 ? 1 : tasks[tasks.length - 1]?.id + 1;
const newTask = { id, ...task };
setTasks([...tasks, newTask]);