parcel icon indicating copy to clipboard operation
parcel copied to clipboard

Emit `parcelhmrapplied` event, mirroring `parcelhmraccept`

Open rexxars opened this issue 1 year ago • 2 comments

↪️ Pull Request

This PR introduces a new parcelhmrapplied event, which is triggered (as the name implies) after the updates have been applied.

I'm also wondering if a PR to emit another event would be considered - one that fires after Refresh.performReactRefresh() has been called in the react-refresh-wrap transformer. That would make it easier to know when the updates have actually rerendered. Thoughts?

💻 Examples

There are cases where hot module reloading is too granular in what it updates. For instance, a React error boundary can take children as a prop, which means it is not marked as depending on the things it does render down the tree. This can be problematic because the error boundary holds any encountered error in its local state, and does not know to reset after an updates module has been received.

By listening for HMR events, an error boundary can however manually reset its error state upon successful application of updates. Unfortunately, the current event (parcelhmraccept) is emitted before the updates have been applied, which is too early to reset - re-rendering immediately will use the hold code and trigger the same error.

🚨 Test instructions

I didn't find any tests for the current event, and the HMR tests I did find were more about the emitting process and such - but the change is fairly trivial. I can try to add a test if you have any pointers to where it might belong.

You can test this manually by opening the devtools on an HMR-enabled page and running window.addEventListener('parcelhmraccept', () => console.log('updates applied')), then triggering an HMR event by modifying a file.

✔️ PR Todo

  • [ ] Added/updated unit tests for this change
  • [x] Filled out test instructions (In case there aren't any unit tests)
  • [ ] Included links to related issues/PRs

rexxars avatar Aug 26 '22 20:08 rexxars

By listening for HMR events, an error boundary can however manually reset its error state upon successful application of updates.

Do you know if this is somehow exposed when using Webpack?

mischnic avatar Aug 29 '22 09:08 mischnic

Do you know if this is somehow exposed when using Webpack?

Yes, Webpack exposes an import.meta.webpackHot.addStatusHandler() function you can use.

rexxars avatar Aug 29 '22 22:08 rexxars