Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

236
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda