immerjs / immer

Create the next immutable state by mutating the current one

Home Page:https://immerjs.github.io/immer/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Immer overwrites properties

yasinitskyi opened this issue · comments

Trying to create alternative object build with produce, but everything comes down to immer overwriting properties every time in the loop:
Original:
Screen Shot 2022-12-09 at 4 01 45 PM
Produce alternative:
Screen Shot 2022-12-09 at 4 04 06 PM
Can someone explain to me how to make alternative version to be working as one with spreads? Thank you!

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:
telegram-cloud-photo-size-5-6095916125268325584-y
This is produce:
telegram-cloud-photo-size-5-6095916125268325585-y
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