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

235
Views
¿Cómo puedo hacer un valor predeterminado para no obtener un NaN?

Estoy codificando un rastreador de tareas cuando puede agregar y eliminar tareas. Cada tarea tiene un valor de identificación y cuando agrega una nueva tarea, la identificación será la última + 1. Si elimino todas las tareas y luego agrego una, la identificación será NaN. Me gustaría obtener ayuda :)

Tareas -

 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, }, ]); };

al agregar tarea -

 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

Presumiblemente, esto podría resolverse como null aquí:

 tasks[tasks.length - 1]?.id

Pero puede proporcionar un valor predeterminado de 0 cuando eso suceda:

 tasks[tasks.length - 1]?.id ?? 0

Entonces, esto siempre debería resolverse al menos en un número válido:

 const id = (tasks[tasks.length - 1]?.id ?? 0) + 1;
about 4 years ago · Juan Pablo Isaza Report

0

Puede asignar condicionalmente un valor a id de la siguiente manera:

verificaremos si la matriz de tareas está vacía o no, si está vacía, estableceremos id=1 , de lo contrario, seguiremos con la lógica regular

 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!