DEV Community

Discussion on: Prefetching Data in a Next.js Application with SWR

Collapse
 
julioocz profile image
Julio Navarro

Cool article! It sounds great the idea of the prefetching.

I have a few concerns though:

  • What happens to the request if the user immediately clicks the the nav item and the request hasn’t resolve? Do it continues and there is some gains from it or SWR just drops the request? A lot of the times a user is going to another route it clicks it immediately.

  • It looks like going with this approach requires to no use getInitialProps which is one of the main next.js features, do you think it’s worth the tradeoff?

Collapse
 
sergiodxa profile image
Sergio Daniel Xalambrí • Edited

Good questions, for the first one it depends on how you use mutate, basically you have two ways.

  1. Call mutate(key, data)
  2. Call mutate(key, promise)

If you use the first one you will need to await for the fetch to resolve and then call mutate.

function fetchAndCache(key) {
  const data = await fetcher(key);
  mutate(key, data, false);
  return data;
} 

Something like that, that works most of the time but if the users immediately click the link to navigate to a page it will start a new request because it doesn't know you are already fetching the data somewhere else, this could cause a race condition where the second request (the one started by SWR itself) resolves faster than the first one (started by your prefetching), in that case we want only the second one to be used but the first one will overwrite the second one.

If we use the second way passing the promise what will happen is that SWR will know a request for that cache key is running, once the user navigate to the page using the same key SWR will avoid running a request immediately and wait for the promise to resolve. So no race condition here.

And if the user ends up clicking on another route what will happen is that you fetched the data but you didn't needed it, in that case the data will be cached and nothing else happens, the only downside is that you prefetched something and you are not using it yet, but it wouldn't negatively affect you.

About your second question, I'm not using getInitialProps anymore, Next.js detects the usage of it to do SSR and if you are not using it, it does SSG, basically I only let Next.js render the loading state of each page to an HTML and then load the whole data client side, as a JAMStack application, if a request fails because the user is not authenticated I'm throwing an error and using error boundaries to redirect to the login page.

I think handling data fetching this way makes easier to handle error like the unauthorized cases. Using SSG will also gives you better performance than doing SSR.