Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Best way to merge partial object into nested draft?#98

Answeredbyunadlib
Adam-Beno asked this question inQ&A
Discussion options

Hey! 👋
I've just discovered this library and I'm currently integrating it into one of our React components. I ran into a situation where I need to merge a Partial object into a nested object within a draft.

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...});
You must be logged in to vote

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

Comment options

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);});
You must be logged in to vote
0 replies
Answer selected byAdam-Beno
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Q&A
Labels
None yet
2 participants
@Adam-Beno@unadlib

[8]ページ先頭

©2009-2025 Movatter.jp