Saving Form Edits
We'll cover the following...
We can now edit a draft item, but when we click “Stop Editing”, the original item is still unchanged. We need to overwrite the values in the original entry with the updated values in the draft entry.
Updating Existing Models
Earlier, we wrote a function called copyEntity
, which serializes the requested model (and its relations) to plain JS objects, and recreates them in the draft slice. We now need to reverse the process, but this gets a bit tricker. We already have an entry in the entities
slice, so we can’t just call createEntity()
on that slice. If we tried deleting it and immediately recreating it with the new values, Redux-ORM would also clear out all the relational fields that reference that same item, which would break things. What we really need is a way to update the existing model “in-place”.
This is the other part that Tommi Kaikkonen helped me figure out. We can write custom updateFrom()
methods on our Model classes, which take another model of the same type, and recursively update themselves and all their relations. It’s basically the inverse operation of the sample toJSON()
function I showed earlier.
toJSON() {
return {...this.ref};
}
+ updateFrom(otherPilot) {
+ this.update(otherPilot.ref);
+ }
}
Again, our current model classes don’t have any complex relations, so the implementation is really simple. We just call the built-in update()
method, and pass it the plain JS object that the other model wraps around (which, in our case, is stored in the other slice of state).
The process of updating a 1:many ...