Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

242
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda