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

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

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 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