hashicorp / next-remote-watch

Decorated local server for next.js that enables reloads from remote data changes
Mozilla Public License 2.0
349 stars 17 forks source link

Support Fast Refresh #42

Open gaearon opened 1 year ago

gaearon commented 1 year ago

I'm curious if it's possible to add Fast Refresh support instead of reloading the page.

I made it work for myself with a hack.

I replaced this line:

https://github.com/hashicorp/next-remote-watch/blob/53278dac1c44005dc197c2d4e199ac39cffb5be2/bin/next-remote-watch#L98

with this:

          app.server.hotReloader.send({
            event: 'serverOnlyChanges',
            pages: [
              '/[[...markdownPath]]'  /* my app only has this one route */
            ]
          });

So, basically fooling Next (via undocumented API) into thinking I updated getStaticProps so it needs to refetch that page.

gaearon commented 1 year ago

For context, here's the rest of my setup. I forgot I didn't actually use next-remote. https://twitter.com/dan_abramov/status/1566982560433029120

ramblehead commented 1 year ago

Thinking from a slightly different perspective - what about to continue using reloading as a more generic approach and preserve states that matter for content editing in the session storage between reloads?

This is what I have in my _app.tsx:

if (process.env.NODE_ENV === 'development') {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    const scrollPos = sessionStorage.getItem('rh-scroll-pos');
    if (scrollPos != null) {
      window.scrollTo(0, Number(scrollPos));

      // In case if browser mistakenly preserves sessionStorage
      sessionStorage.removeItem('rh-scroll-pos');
    }

    window.addEventListener('beforeunload', (_event) => {
      sessionStorage.setItem('rh-scroll-pos', String(window.scrollY));
    });
  }, []);
}

it should work with manual reloads too.

(the idea is stolen from this SO)

gaearon commented 8 months ago

For people using App Router, here's how I'm doing the same manually: https://github.com/gaearon/overreacted.io/pull/797