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

115
Views
How to change a nested object value of a redux state

I have the following state

const state = {
  courses: [],
  series: [],
  course: {
      title: 'testing',
      course_notes: [
    {
      id: 1,
      note: "one" // want to edit this
    },
    {
      id: 2,
      note: "two"
    }
  ]
}
}

I want to change state.course.course_notesp[0].name

I've never fully understood how this works, read a lot of tutorials, I feel I know how it works but it always trips me up. This is what I am trying

const m = {
  ...state, 
  course: {
    course_notes:[
      ...state.course.course_notes,
      state.course.course_notes.find(n => n.id === 1).note = "edited"
    ]
  }
}

That seems to add edited as an extra node. state.course.course_notes.length ends up being 3.

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

0

There are lots of ways you could modify the state of your store to update one element of course_notes.

If we assumed the ids to be unique, I would map the previous array modifying the element with id 1.

....
course_notes: state.course.course_notes.map(x => x === 1
  ? { ...x, note: 'edited' } 
  : x
)
...
about 4 years ago · Juan Pablo Isaza Report

0

You are using the spread operator for arrays like you would for objects.

Assume you have an object

const obj = { a: 1, b: 2 }

If you say:

{...obj, a: 2}

What you are saying is:

{ a: 1, b: 2, a: 2 }

The property a is defined twice, but the second one overrrides the first one.

If you do something similar for an array, however, the result would be different:

const arr = [1, 2];
const newArr = [...arr, arr[0]];

// here the result would be [1, 2, 1]

This is why when you are saying:

course_notes:[
  ...state.course.course_notes,
  state.course.course_notes.find(n => n.id === 1).note = "edited"
]

what it does is add an extra element to the array.

What you should do is instead create a modified version of the array, for example using map

course_notes: state.course.course_notes.map(el => {
    if (el.id === 1) {
        el.note = 'edited';
    }
    return el;
});
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!