Snowpack - HMR - Compare Old and New Value

01/29/2022, Sat
Categories: #shell #JavaScript
Tags: #NodeJs

Export Value for Comparison

HMR is a convenient tool to have when one wishes to perform updates to a page without fully reloading the whole page. When using Snowpack's HMR, one can compare a variable's value prior to it being changed.

This feature might come in handy when you want to perform resets after a set amount of time has passed for a user session, but there also might be a requirement to restore certain pieces of old information back into a new session. For example, in a privacy-sensitive form area, a notice can come up in area that does not require a full refresh as a top status bar after a time-out period.

While there might be other cases that HMR will come into play, the following example below will illustrate the saving and retrieval of a variable value which that could be used later for comparison and manipulation.

// Sample variable to watch for changes
// must be exported
export let myVar = 5;

// Add the following your entry point .js file
if (import.meta.hot) {

  // Area to compare old with the new changed value
  import.meta.hot.accept(({module}) => {

    // Recently changed state value
    console.log('module.myVar', module.myVar);

    // Prior value before the changed state value
    console.log(import.meta.hot.data.myVar);

    // Current myVar value will become the old variable value
    myVar = module.myVar;
  })

  // Area to save prior variable value for comparison later
  import.meta.hot.dispose(() => {

    // Save state before destroying the current module.
    import.meta.hot.data = { myVar };
  })
}

More details from the official snowpack esm-hmr repository.