2

I have a component the displays data and is updateable.

When the component loads it queries for data. When I get the results back I store a modifiable version in a variable and a deep cloned copy of the original data.

When I click cancel the modifiable data gets replaced with the original data. This works perfectly fine when I click edit, make a change, and hit cancel.

But if I click the save button, which actually doesn't save anything it just changes the form back to the view mode, click edit again, and click cancel my original data model somehow gets replaced as well.

Playground

Steps to reproduce

  • Observe Original Value
  • Click Update
  • change value
  • Click cancel
  • Observe the original value is persisted
  • Click update
  • change value
  • Click save
  • click update
  • click cancel

The expect behavior is that since Save doesn't actually persist any changes, the next cycle of update and cancel should restore it to the original value

Where does my originalData variable get changed?

5
  • +1 nice question – salesforce-sas Aug 21 '19 at 19:26
  • When loading the page i get "SecurityError. An attempt was made to break through the security policy of the user agent." – battery.cord Aug 22 '19 at 13:59
  • What browser? @battery.cord – TemporaryFix Aug 22 '19 at 14:00
  • Chrome 75. I think its just something with the lightning playground, I'm getting it for both the question & answer. – battery.cord Aug 22 '19 at 14:11
  • hmmm I'm unsure. I'm using chrome 76 – TemporaryFix Aug 22 '19 at 14:30
2

I created a new simpler Playground example to understand better.

Reason:

When you say this.data = this.originalData, it means you are allocating same memory location to both this.data and this.originalData. You are doing this on cancel in toggleEdit method`

In the above playground link notice the usage of this.data = { ...this.originalData } in toggleEdit method. This will essentially clone the objects by allocating separate memory.

There is another commented line this.data = this.originalData.

Now, try editing and cancelling alternative by commenting/uncommenting above lines - you will notice the difference.

1
  • 2
    It's as clear as day once you finally notice it. This really took me for a ride. This is the second day you've helped me, thanks! – TemporaryFix Aug 21 '19 at 19:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.