3

This document - Modifying Components Outside the Framework Lifecycle - says the following:

You don't need a cmp.isValid() check within this setTimeout() call as the cmp.set() call doesn't do anything when the component is invalid.

window.setTimeout(
    $A.getCallback(function() {
        cmp.set("v.visible", true);
    }), 5000
);

Whereas Trailhead - Secure Your Lightning JavaScript Code (Asynchronous JavaScript) - states quite the opposite:

If you want your function to access data in a Lightning component, you can always reach the framework with the $A.getCallback() closure. Use cmp.isValid() inside the closure to check that your component still exists.

waitAndChange: function(cmp,evt,hlp){ 
  setTimeout(function(){ 
    $A.getCallback(function(){ // access the framework in a closure 
      if(cmp.isValid()){ // does the component exist in this context? 
        cmp.set("v.resultAttr","new value");
      } 
    }); 
  }, 2000);
}

With that being said, when and why do I need to perform `cmp.isValid()' check?

1 Answer 1

3

I think you are not forced to use it if you don't want. The second warning seems like just a good practice information. It reminds you to use .isValid() because you might do something inside the callback that is resource-intensive or difficult to un-do, or something like that.

The Trailhead text states that:

This function checks that its parent component still exists before modifying its data. Without the check, an obtrusive error message prevents the user from interacting with the page.

However, this is not what the source code looks like. The .set method checks if the component is destroyed or not (same thing as .isValid()) before assigning the value.

To me, it sounds like the trail's text is outdated. Luckily you can check this for yourself, destroying a component and trying to set an attribute. If shows an obtrusive error message, then the documentation and the source code are outdated instead (which isn't that unlikely, since the project is archived on GitHub).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .