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

96
Visualizações
updating two state in parallel without using useReducer

In this code when I click the delete button I get this error:

App.js:9 Uncaught TypeError: Cannot read properties of undefined (reading 'map')

I realized the reason is that I must update the state of selectedNumber before updating the numbers state. I understand that it is impossible to do it just with useState. I realized I could do it with useReducer. Am I right or there is another way to do it without useReducer?

import { useState } from "react";

const App = () => {
  const [numbers, setNumbers] = useState([1, 2, 3, 4, 5, 6]);
  const [selectedNumber, setselectedNumber] = useState(1);

  return (
    <div>
      <ul>
        {numbers.map((number) => {
          return (
            <li
              key={number}
              onClick={() => setselectedNumber(number)}
              style={
                number === selectedNumber ? { color: "blue" } : { color: "red" }
              }
            >
              {number}
            </li>
          );
        })}
      </ul>
      <div>
        {selectedNumber}
        <button
          onClick={() =>
            setNumbers((prev) => {
              prev.filter((number) => number !== selectedNumber);
            })
          }
        >
          delete
        </button>
      </div>
    </div>
  );
};

export default App;
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You're not returning anything in the callback passed to setNumbers. So, undefined will be returned and the new state becomes undefined leading to undefined.map(...

<button
    onClick={() =>
        setNumbers((prev) => {
            return prev.filter((number) => number !== selectedNumber);
        })
    }
>
    delete
</button>

btw, useReducer is not needed as your state is not that complex

about 4 years ago · Santiago Trujillo 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