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.
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
)
...
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;
});