• Benjamin Doctors
  • NEWBIE
  • 0 Points
  • Member since 2022

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 2
    Replies
Hi Devs,
I'd finished the Input Data Using Forms unit from Aura Components Basics module and in some part they use a JSON.parse(JSON.stringify()) and call it a DISGUSTING TEMPORARY HACK.
My problem is that I don't understand why are they using that.
As far as I know, JSON.parse(JSON.stringify()) clones an object (use with care since can give strange results sometimes), but I don't get why clone when you already have the object.
Even worse, I removed that line of code and everything seems to work perfectly.
 This is all the explanation in the unit: 
"The “disgusting hack” works around a similar issue with references. To see the issue, change the line to remove the two JSON calls, and test the app. You’ll see what the problem is quickly enough. We’ll remove it in the next unit, and so won’t explain further."
The misterious hack is in the helper.js file.
({
    createExpense: function(component, expense) {
        let theExpenses = component.get("v.expenses");
        // Copy the expense to a new object
        // THIS IS A DISGUSTING, TEMPORARY HACK
        let newExpense = JSON.parse(JSON.stringify(expense));
        theExpenses.push(newExpense);
        component.set("v.expenses", theExpenses);
    }
})
Please, help me understand this hack.

Regards,

Benja
 
I'm facing an error on my Trailhead account. My certifications aren't appearing, and the error below occurs when I try to connect my web assessor account. Could you please help? Thanks,
User-added image
In the Lightning Components Basics -> Input Data Using Forms module the controller that looks like this:
({
    createExpense: function(component, expense) {
        var theExpenses = component.get("v.expenses");
 
        // Copy the expense to a new object
        // THIS IS A DISGUSTING, TEMPORARY HACK
        var newExpense = JSON.parse(JSON.stringify(expense));
 
        theExpenses.push(newExpense);
        component.set("v.expenses", theExpenses);
    }
})

And this comment later on in the text:
The “disgusting hack” works around a similar issue with references. To see the issue, change the line to remove the two JSON calls, and test the app. You’ll see what the problem is quickly enough. We’ll remove it in the next unit, and so won’t explain further.

It seems to me the purpose of this is to create a copy of the expense object, rather than treating it as a reference.  Am I right? Also, why?  The text says I'll see the problem quicky enough but I don't.  I removed the stringafy and parse and the code still seems to work just fine.

Just trying to understand.  Thanks.