Immer overwrites properties
yasinitskyi opened this issue · comments
Can you post a code snippet instead and examples with what you are trying to achieve and get? Images aren't editable. But I imagine it'd be something like this draft[canvas.format.platformType][canvas.format.platform].groups[group.name] = group
in the inner forEach.
@mweststrate it will throw an Error since the draft is empty in the beginning, as you can see, it is an empty object passed as initial value for produce, so once you tried to dig through the chain of properties it will exit immediately.
This is what i am getting with version with spreads:
This is produce:
Code snippets:
processPurposes() { const platforms = {}; this.layout.compositionGroups.forEach((group) => { group.canvasses.forEach((canvas) => { platforms[canvas.format.platformType] = { ...platforms[canvas.format.platformType], [canvas.format.platform]: { groups: { ...platforms[canvas.format.platformType]?.[canvas.format.platform]?.groups, [group.name]: group, }, }, }; }); }); console.log('platforms: ', platforms); }
processPurposesNew() { const basePurposes = {}; const handlePurposes = produce((draft) => { this.layout.compositionGroups.forEach((group) => { group.canvasses.forEach((canvas) => { draft[canvas.format.platformType] = { [canvas.format.platform]: { groups: { [group.name]: group, }, }, }; }); }); }); const nextPurposes = handlePurposes(basePurposes); console.log('platforms: ', nextPurposes); }
Data:
[ compositionGroup1: { name: horizontal canvasses: [{format: {platformType: social_media, platform: GDN}}] } compositionGroup2: { name: square canvasses: [{format: {platformType: social_media, platform: INSTAGRAM}}] } ]
@mweststrate Any suggestions how to make it clean, example of code snippet maybe? Or I dont need produce in this example and can use spread version of it? I just imagine if nesting will be even more complex... Thank you
const x = a.b.c;
if (!x.y) {
x.y = {}
}
x.y[z] = w
or: (a.b.c.y ??= {})[z] = w
, but the readability improvement could be contested