Next.js

ℹ️
React Hooks for Data Fetching.
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.
 

Installation

$ yarn add swr or $ npm install swr

Usage

For normal RESTful APIs with JSON data, first you need to create a fetcher function, which is just a wrapper of the native fetch:
const fetcher = (...args) => fetch(...args).then(res => res.json())
Then you can import useSWR and start using it inside any function components:
import useSWR from 'swr' function Profile () { const { data, error } = useSWR('/api/user/123', fetcher) if (error) return <div>failed to load</div> if (!data) return <div>loading...</div> // render data return <div>hello {data.name}!</div> }
In this example, the useSWR hook accepts a key string and a fetcher function. key is a unique identifier of the data (normally the API URL) and will be passed to fetcher. fetcher can be any asynchronous function which returns the data, you can use the native fetch or tools like Axios.
The hook returns 2 values: data and error, based on the status of the request.

Make it Reusable

It is incredibly easy to create reusable data hooks on top of SWR:
function useUser (id) { const { data, error } = useSWR(`/api/user/${id}`, fetcher) return { user: data, isLoading: !error && !data, isError: error } }
And use it in your components:
function Avatar ({ id }) { const { user, isLoading, isError } = useUser(id) if (isLoading) return <Spinner /> if (isError) return <Error /> return <img src={user.avatar} /> }

Leave a comment