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

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

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 Denunciar

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