Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
How can I make a default value so I won't get an NaN

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]);
};
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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;
about 4 years ago · Juan Pablo Isaza Report

0

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]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!