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

140
Views
Conditionally add key/value pairs of two separate objects (one in array within initial state) for array method inside of useState() hook

Right now, this doesn't work.

const item = {name: "mike", apples: 20}

const [list, setList] = useState([{name: "peter", apples: 30}, {name: "mike", apples: 39}])

setList(list.map(entry => entry.name == item.name ? entry.apples = item.apples+entry.apples : entry = entry))

I am able to get it working with the code below. I know it's not clean and that's why I'm trying to get the top code working the react way: using es6 within useState hook.

  let newList = [...list]
  let changed = false
  newList.map(entry => {
    if(entry.name == item.name) {
      entry.apples = item.apples+entry.apples
    }
  if(changed) {
    setList(newList)
  }

Edit: I've also tried functional update on the state like below

setList(list => list.map(entry => entry.name == item.name ? entry.apples = item.apples+entry.apples : entry = entry))
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Here's the right way:

setList((previousList) =>
  previousList.map((entry) =>
    entry.name == item.name
      ? { ...entry, apples: entry.apples + item.apples }
      : entry
  )
);

entry.name == item.name ? entry.apples = item.apples+entry.apples

will not work because entry.apples = item.apples+entry.apples returns apples, but each element of the array should remain an object and you should also make sure that the state is not mutated (entry.apples = ... is bad because entry is mutated)

about 4 years ago · Juan Pablo Isaza 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!