useSWR
Author : JaNakh Pon , August 14, 2021
Tags
Intro
The name “SWR” is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861. 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.
SWR works with three main steps: first, it returns the data from the cache (the stale part), then sends the fetch request (the revalidate part), and finally comes with the up-to-date data. But no worries, SWR handles all these steps for us. The only thing we have to do is give the useSWR hook the needed parameters to make the request.In this post, we'r going to build a simple demo app using React.js and Github public api.
Installation
Let's get started by generating a react app using create-react-app:
> npx create-react-app swrgithubdemo --template typescript
> cd swrgithubdemo
Now we have a react app with typescript, so let's install swr:
> npm install swr
Summary
The main concept in this app will be fetching data from Github api using axios with swr. useSWR will cache the data of the route and will pass the data from the cache if we call the same route again while revalidating it in background.
There are many more awesome features provided by SWR and one of them is Auto Revalidation because with that feature, SWR make it easy for us to revalidate data in various ways(Revalidate on Focus, Revalidate on Interval, Revalidate on Reconnect)
Ok, let's get back to Implementation 😉,
Our demo app has ✌️ main parts:
- fetching List of repository from Github, display it
- buttons for Pagination, change page value onClick
For repo list, swr+axios will fetch the list of repo for a specific page and loop that data and display each repo name, language and datetime.
And for Pagination, we will loop the button for Pagination for a number of x time and set the page value according to the button number onClick.
import { useState } from 'react'
import useSWR from 'swr';
import moment from 'moment';
import { fetcher } from './utils'
const App = () => {
const [page, setPage] = useState<number>(1)
const { data, error } = useSWR<any[]>(
`repos?per_page=15&page=${page}`,
fetcher, { refreshInterval: 10000 }
);
return (
<div className="container mx-auto my-5 ">
{
error ? (<>
<div className="flex justify-center mt-5 mx-8">
<section className="w-10/12 sm:w-10/11 lg:w-1/2 max-w-2xl flex justify-center">
<h1 className="text-9xl text-bolder text-red-700"> ERROR </h1>
</section>
</div>
</>) : (<>
{
!data ? (
<>
<div className="flex justify-center mt-5 mx-8">
<section className="w-10/12 sm:w-10/11 lg:w-1/2 max-w-2xl flex justify-center">
<h1 className="text-8xl text-bolder text-yellow-700"> Loading ...... </h1>
</section>
</div>
</>
) : (
<>
<div className="grid grid-flow-row auto-rows-max lg:mt-5 sm:mt-2">
{
data.map((repo: any, i: number) => {
return (
<div className="flex justify-center mt-5 mx-8" key={i}>
<section className="w-10/12 sm:w-10/11 lg:w-1/2 max-w-2xl">
<h2 className="font-bold ml-2">{repo.name}, <span className="font-light text-xs">{moment(repo.created_at).fromNow()}</span></h2>
<p className="text-left text-sm px-1 text-gray-700">
Language: {repo.language}
</p>
</section>
</div>
)
})
}
</div>
<div className="flex justify-center mt-5 mx-8">
<section className="w-10/12 sm:w-10/11 lg:w-1/2 max-w-2xl flex justify-center">
<nav aria-label="Page navigation">
<ul className="inline-flex space-x-2">
{
[...Array(10)].map((val, i) =>
<li key={i}>
<button className={`w-10 h-10 ${i + 1 === page ? " text-white transition-colors duration-150 bg-gray-500 border border-r-0 border-gray-500 rounded-full focus:shadow-outline" : "transition-colors duration-150 rounded-full focus:shadow-outline hover:bg-gray-100"} `} onClick={() => setPage(i + 1)}>{i + 1}</button>
</li>
)
}
</ul>
</nav>
</section>
</div>
</>
)
}</>)
}
</div >
);
}
export default App;
Btw this article about SWR on smashingmagazine is awesome!!!, also SWR official doc!.
Go Back.