- Notifications
You must be signed in to change notification settings - Fork23
-
Hey! 👋 However, I don’t see an obvious way to do this without using the spread operator which feels a bit off, since avoiding things like spread and Object.assign seems to be one of the core ideas behind this library. Is there a recommendedMutative way to apply partial updates to nested objects? Thanks in advance! Example: interfaceStep{id:string;name:string;status:string;progress:number; ...}interfaceJob{id:string;steps:Record<string,Step>; ...}const[jobs,setJobs]=useMutative<Record<string,Job>>({});...constjobId="...";conststepId="...";constpartialStep:Partial<Step>={name:"...",status:"...",};setJobs((draft)=>{constjob=draft[jobId];if(!job){return;}// This is what im trying to do, but it's obviously wrongjob.steps[stepId]=partialStep;// Spread operation?job.steps[stepId]={ ...job.steps[stepId], ...partialStep};// Assign manually? I dont wanna do that as the object could growjob.steps[stepId].name=partialStep.name;// Loop the partial? gonna be calling lots of updates so i try to avoid loops...}); |
BetaWas this translation helpful?Give feedback.
All reactions
hi@Adam-Beno ,
To be clear,Object.assign and the spread syntax (...) are not equivalent. We can also useObject.assign to perform mutations.
In your example, it could be done like this:
setJobs((draft)=>{constjob=draft[jobId];if(!job){return;}Object.assign(job.steps[stepId],partialStep);});
Replies: 1 comment
-
hi@Adam-Beno , To be clear, In your example, it could be done like this: setJobs((draft)=>{constjob=draft[jobId];if(!job){return;}Object.assign(job.steps[stepId],partialStep);}); |
BetaWas this translation helpful?Give feedback.