Issue
I have nested objects and would like to change only the value of one property within a nested object.
I tried to patch, immer, but in all cases I do not understand why it is not possible.
It is sometimes reported that the property is read-only, sometimes the object is not extensible.
Using patch, I'm not able to because it requires all object properties to be entered.
And since the object has other objects and many other properties, I would like to just update one property.
Clearly I'm doing something wrong.
@Action(SetPropertyValueAction)
public setPropertyValueAction(ctx: StateContext<OneStateModel>, { propertyValue }: SetPropertyValueAction) {
// Of course this does not work, but it is to show what I need to happen.
const state = ctx.getState();
const obj = state.obj;
obj.object1.object2.object3.property1 = propertyValue;
ctx.patchState({ obj });
// I would like to do something like that, but I can't.
ctx.patchState({
obj: {
object1: {
object2: {
property1: propertyValue
}
}
}
});
}
The problem is that the object has a complex structure and I can't report all of its properties.
obj: {
prop1: number,
prop2: number,
prop3: number,
object1: {
prop1: number,
prop2: number,
object2: {
prop1: number,
prop2: number
}
},
}
Solution
When u use the store patter u never modify any object in the store. U need one new object with the changes. Use the spread operator ...
to make this more easy.
ctx.setState({
...state,
obj: {
...state.obj,
object1: {
...state.obj.object1,
object2: {
...state.obj.object1.object2,
object3: {
...state.obj.object1.object2.object3,
property1: propertyValue,
},
},
},
},
});
Answered By - Manuel Panizzo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.