[SalesForce] way to destroy LWC from its js controller

I would like to know if there is a way to destroy LWC component from its js controller. I know in Aura there is something called component.destroy() method. But in lwc I couldn't something like that. Please shed some light on this.

The problem I am facing is, I have created a 'New' page for opportunity with LWC and upon submitting, navigating to the view page. But after that when I come back to opportunity 'New' page, at times, the page doesn't load or the form with previous values is being shown. Hence I would like to destroy the current component after navigating to view page.

Best Answer

From the documentation of Component.destroy()

If you create a component dynamically in JavaScript and that component isn't added to a facet (v.body or another attribute of type Aura.Component[]), you have to destroy it manually using Component.destroy() to avoid memory leaks.

Now in LWC you cannot create components dynamically yet. Thus there is no destroy as of now.

When a user navigates to a different page, components on the previous page remain in the cache and are hidden, not destroyed

I get this is causing your component to hide and when refocussed to show old values. For this scenario, if you are using UI Api or cacheable then you can call refreshApex before redirecting to ensure when the component is focuccesd again, it will have latest values.

Related Topic