loader

Using SWR for Data Fetching in NextJS

Ugur Emirmustafa

Feb 19, 2021
–––
NextJS

Share

SWR is a react hooks library for data fetching created by Vercel - the team created NextJS also. It is the shorthened form of stale-while-revalidate. "SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data." as mentioned on their website.

It is bundled with NextJS so you don't need to install it externally if you are using NextJS already in your app.

In order to fetch data with swr we can use useSWR hook from swr.

import useSWR from 'swr'

useSWR hook can be used with a custom data fetching function. I will use native fetch function to create my custom function.

const fetcher = (...args) => fetch(...args).then((res) => res.json());

This function pushes the arguments to the fetch and returns the response as json data in the then block. Now we can use the useSWR hook with our custom fetcher function.

function Home() {
  const url = 'https://jsonplaceholder.typicode.com/todos';
  const { data, error } = useSWR(url, fetcher);
  
  if(!data) return <div>Loading...</div>
  if(error) return <div>there is an error!</div>

  return (
    <div>
      {JSON.stringify(data, null, 2)}
    </div>
  );
}

export default Home;

We pass the url and fetcher to the useSWR hook and we get an object from it which includes the data and the error items. If there is no data it means it is in loading state, so we return a div with loading text. If there is an error we pause the flow and return an error message. And finally if we pass these steps, we return the data as json string.

Normally whenever we change our tab or lose focus on window and turn back to that window and gain focus again, useSWR will fetch the latest data again. By this feature you are sure that your data is updated. But sometimes you may want to close this feature. You can achive it by passing another parameter to the hook.

  const { data, error } = useSWR(
      url, 
      fetcher, 
      { revalidateOnFocus: false }
    );

You can check the network tab in the developer console with and without this parameter.

https://cdn.sanity.io/images/tyoef2gl/production/63fc1bf60aec5501bdd972a5a8de548ec3ce08fd-2718x1402.gif?rect=191,0,2337,1402&w=750&h=450&fit=max&auto=format

And that is for all know. We will discuss mutate feature of swr later and this post will be updated.

Don't forget to follow me on twitter

More Posts

loader

Create Custom Social Share Buttons for React

Feb 17, 2021

–––
loader

HTML Link in A New Tab

Feb 19, 2021

–––

Follow Me!

dev

ugur