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

95
Views
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 answers
Answer question

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