
SWR: React Hooks for Data Fetching
SWR is a React Hooks library for data fetching. SWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.
https://swr.vercel.app/
import useSWR from 'swr'
function Profile() {
//SWR always returns data and error
const { data, error } = useSWR('/api/user', fetcher)
//there are three basic data states:
//error, loading, and data
//these handle the first two
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
//display data
return <div>hello {data.name}!</div>
}
To install just do npm install swr.
Make a simple fetcher function to pass to useSWR
.
const fetcher = (...args) => fetch(...args).then(res => res.json())
To make it reusable, just pass useSWR
to a function.
function useUser (id) {
const { data, error } = useSWR(`/api/user/${id}`, fetcher)
return {
user: data,
isLoading: !error && !data,
isError: error
}
}
Then pass them into your conponents:
function Avatar ({ id }) {
const { user, isLoading, isError } = useUser(id)
if (isLoading) return <Spinner />
if (isError) return <Error />
return <img src={user.avatar} />
}