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

80
Views
How do I update array inside object in redux

I have an array I'm writing a code for redux now.

const initialState = [{ id: '1', title: '', description: '' }];

I would like to update that array like this

[{ id: '1', title: '', description: '' },{ id: '2', title: '', description: '' }];

and after copying I want to update the copy one of id to '2'

here is what I tried

    case COPY_QUESTION: {
      const copyQuestion = state.find(question => question.id === action.payload)
      copyQuestion?.id = (state.length + 1).toString()
      return [...state, copyQuestion];
    }

it didn't work for me. if I try to change id, the 0 index changes too at the same time. like this

[{ id: '2', title: '', description: '' },{ id: '2', title: '', description: '' }];

I would really appreciate your help thanks for reading this question.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Something like this should work:

const initialState = [{ id: '1', title: '', description: '' }];

const copyInitialState = [...initialState]

copyInitialState.push({ id: parseInt(copyInitialState[copyInitialState.length - 1].id, 10) + 1, title: '', description: '' })

//setState

copyInitialState is then equal to:

[
 {
  id:"1",
  title:"",
  description:""
 },
 {
  id:2,
  title:"",
  description:""
 }
]
about 4 years ago · Juan Pablo Isaza Report

0

JavaScript handels Objects by reference and therefore ’find’ only returns the address in memory of the already existing object, which you then manipulate.

You have to clone your object first, e.g. using the spread operator (not for deep clones):

const originalQuestion = state.find(question => question.id === action.payload)
const copyQuestion = { ...originalQuestion }

Have a look at this SO question for more context and possibilities.

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!