niko craft
niko craft

Reputation: 2987

update original object with values from server after ajax post

I make a call to server and save some stuff, after successfull save I need to update the json array object I have with new values. Here is some of my code

[
  {
    "id": 1,
    "uuid": "ce54acea-db20-4716-bceb-2f3deb1b2b86",
    "name": null,
    "order": 1,
    "children": []
  }
]

I got an array of object, they can be nested inside each other as well.

After I edit a specific object I can chose to save the new values to the server. After Save button is pressed and before I send data to server I store a reference to the object being edited. I store this refefence inside

selectNode = function(clickedNode) {
  this.selectedNode = clickedNode
  this.tempNode = _.clone(clickedNode)
}

I have a temp object here because the user can press Cancel button as well and that means any changes need to be discared as well. So I make a reference to the object being edited and then make tempNode object which I actually edit and upon Save push to server.

My problem is that after the successfull save I would like to update all values inside the reference object as well.

Right above I have just few values, but in my app every node will be have lots of values so I do not want to be doing this

    this.http
        .put("/api/manage/v1/"+this.tempNode.uuid, this.tempNode)
        .map(res => res.json())
        .subscribe((data) => {
            this.selectedNode.name = this.tempNode.name
            this.selectedNode.order = this.tempNode.order
            ... and so on, this list could get long and not manageable after while
        }, (error) => {
            console.log(error)
        }
    );

I also tried to do this in the same place replacing the above with

this.selectedNode = _.merge({}, this.selectedNode, this.tempNode);

but this destroys the reference and creates new object so the original object inside a json array never gets updated and ofc nothing gets then updated on the screen either.

Is there a way to automate this

            this.selectedNode.name = this.tempNode.name
            this.selectedNode.order = this.tempNode.order
            this.selectedNode.etc= this.tempNode.etc
            this.selectedNode.etc= this.tempNode.etc7

to one line of code where all values get copied to referenced object without destroying the reference with new object?

Upvotes: 0

Views: 27

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371138

If you want to keep the reference, you can use standard Object.assign to assign all properties of tempNode to selectedNode without reassigning selectedNode:

.subscribe((data) => {
  Object.assign(this.selectedNode, this.tempNode);

Object.assign (and _.merge, presumably) mutates the first argument, and you want mutation, not reassignment.

Upvotes: 1

Related Questions