4

This LWC lifecycle method is documented as:

Use disconnectedCallback() to clean up work done in the connectedCallback(), like purging caches or removing event listeners.

Not that the set of components this needs to work within is contained i.e. it is not navigating away from the page that is going on but rather buttons and links within the set of components I have control of.

I am looking for a quick (short term) fix where instead of edits made to a component being lost on this call, those changes are saved via a normal async call to some server-side Apex (the same code that a "Save" button calls).

How bad an idea is this? Has anyone done it? (I don't want to code something up that apparently works but is inherently flakey.)

4
  • 1
    what's your use case? are you trying to save something on the server that could potentially be saved on the client, for example, for when a page reloads, or a user navigates away from a view by accident. Why not use the browser's storage api's to "save" the data?
    – glls
    Aug 19 at 18:38
  • Hi @glls, I am trying to add a simple short-term work-around for a demo. I have some other options such as co-ordinating using LMS and popping up a dialog but that will take a lot more work.
    – Keith C
    Aug 19 at 19:11
  • how much data or properties are you planning on storing? on the server side, does it all link up to a single object?
    – glls
    Aug 19 at 19:28
  • Hi @glls, Typically a few fields on a single object. So looking for a small solution to a small problem...
    – Keith C
    Aug 19 at 19:36
2

As long as you're aware of the limitations of such a setup, and you control all the components, such that the disconnectedCallback is under your direct control, this is a perfectly reasonable solution. Note that if you use window.pushState/window.replaceState and the popstate event, you can manipulate the URL for your app while still having Single Page Application (SPA) functionality; your component can then safely save data when it's disconnected from the DOM. Caution should be used only if you plan on doing this in Lightning Experience or Communities directly, since they have a weird habit of recycling component instances, such that disconnectedCallback may not be called for some time, or at all.

2
  • Thanks for these comments: I'll give it a go and see. Another route is to disable all the buttons/links that cause the data to be lost; might code up both.
    – Keith C
    Aug 19 at 19:37
  • Based on the UX side we've decided to go the other route so I won't find out if there are any gotchas. But appreciate the answer: re-assured us to have the discussion solely on the merits of the UX.
    – Keith C
    Aug 20 at 12:08

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.