Inside reducer, given a state object:
var state = {
"data": [{
"subset": [{
"id": 1
}, {
"id": 2
}]
}, {
"subset": [{
"id": 10
}, {
"id": 11
}, {
"id": 12
}]
}]
}
As you can see, the data is a nested array, with arrays in each of its elements.
Knowning that action.indexToUpdate will be a index for data, I want to update data[action.indexToUpdate].subset to a new array programmatically. For example, if action.indexToUpdate = 0, then data[0] will be updated from
[{"id":1},{"id":2}]
to
[{"id":4},{"id":5}]
In order to do so, I have:
let newSubset = [{"id":4},{"id":5}]
let newState = update(state.data[action.indexToUpdate], {
subset: {
newSubset,
},
})
But when I executed this, it returns error:
TypeError: value is undefined
on the update founction.
I have been looking at the react ducomentation here: https://facebook.github.io/react/docs/update.html but I couldn't really figure out how to do it. Please advise!
Unfortunately, the process of correctly applying immutable updates to deeply nested state can easily become verbose and hard to read. Here's what an example of updating state.first.second [someId].fourth might look like: Obviously, each layer of nesting makes this harder to read, and gives more chances to make mistakes.
Dealing with immutable data in JavaScript is more difficult than in languages designed for it, like Clojure. However, we’ve provided a simple immutability helper, update (), that makes dealing with this type of data much easier, without fundamentally changing how your data is represented.
However, we’ve provided a simple immutability helper, update (), that makes dealing with this type of data much easier, without fundamentally changing how your data is represented. You can also take a look at Facebook’s Immutable-js and the Advanced Performance section for more detail on Immutable-js.
A list of many immutable update utilities can be found in the Immutable Data#Immutable Update Utilities section of the Redux Addons Catalog. Our Redux Toolkit package includes a createReducer utility that uses Immer internally.
Your update will look like
var obj = {"state" : {
"data": [{
"subset": [{
"id": 1
}, {
"id": 2
}]
}, {
"subset": [{
"id": 10
}, {
"id": 11
}, {
"id": 12
}]
}]
}}
return update(obj, {
"state" : {
"data": {
[action.indexToUpdate]: {
"subset": {
$set: [newSubset]
}
}
}
}
})
In case there are other fields in subset, but you only wish to the change the fields at specific index containing other keys, you would write
return update(obj, {
"state" : {
"data": {
[action.indexToUpdate]: {
"subset": {
[id]: {$merge: newSubset}
}
}
}
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With