Reputation: 6723
I have following object
state = {"line": [
{"media": [1, 2, 3 ]},
{"media": []},
{"media": []},
]}
What I need is to remove element in media array.
I try the following
return {
...state, line: [{
...state.line[line_index], media = [
...state.line[line_index].media.slice(0, action.payload.index),
...state.line[line_index].media.slice(action.payload.index + 1)
]
}]
}
but it doesn't work, it replaces media with object.
I don't get how to do it correctly. Can some one please show the way and describe it please
Upvotes: 1
Views: 10605
Reputation: 2075
What you forgot is reassembling the line array properly. Try breaking it down like this:
const changedElement = {
...state.line[lineIndex],
media: [
...state.line[lineIndex].media.slice(0, action.payload.index),
...state.line[line_index].media.slice(action.payload.index + 1)
]
}
return {
...state,
line: [
...state.line.slice(0, line_index),
changedElement,
...state.line.slice(line_index + 1)
]
}
What you want to do is write the current structure of your state:
state = {
line: [
{
media: []
},
{
media: []
}
]
}
What you can then do is making it generic and containing state. So, state
should be a copy of state
(by putting ...state
in it) and line
should be a copy of line
. The only difference between line
and state
is that it's an array. Making an immutable copy of an array is a bit more involved than making such a copy of an object. But in your code, you did this already for your changedElement
.
For a further read on this, you should have a look at immutable update patterns, as these are just recipes you can always reuse: https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns
Upvotes: 5