vercel / swr
Get started
From the repository's own files at 9ed1240a4cf7. Commands have not been executed.
Prerequisites
pnpm@10.33.0+sha512.10568bb4a6afb58c9eb3630da90cc9516417abebd3fabbe6739f0ae795728da1491e9db5a544c76ad8eb7570f5c4bb3d6c637b2cb41bfdcdb47fa823c8649319from package.json
Commands
package.json| Task | Run | What it runs |
|---|---|---|
| build | pnpm run build | bunchee |
| test | pnpm run test | jest |
| lint | pnpm run lint | oxlint . |
Install and use
README.mdimport useSWR from 'swr'
function Profile() {
const { data, error, isLoading } = useSWR('/api/user', fetcher)
if (error) return <div>failed to load</div>
if (isLoading) return <div>loading...</div>
return <div>hello {data.name}!</div>
}
In this example, the React Hook useSWR accepts a key and a fetcher function.
The key is a unique identifier of the request, normally the URL of the API. And the fetcher accepts
key as its parameter and returns the data asynchronously.
useSWR also returns 3 values: data, isLoading and error. When the request (fetcher) is not yet finished,
data will be undefined and isLoading will be true. When we get a response, it sets data and error based on the result
of fetcher, isLoading to false and rerenders the component.
Note that fetcher can be any asynchronous function, you can use your favourite data-fetching
library to handle that part.
View full documentation and examples on swr.vercel.app.
Developing
.github/CONTRIBUTING.mdTo run SWR locally, you can start it with any example in the examples folder. You need to set up the example and run the command in the root directory for overriding SWR and its dependencies to local assets.
First of all, build SWR assets
corepack enable
corepack pnpm install
pnpm watch
Install dependency of the target example, for instance examples/basic:
# by default it will run next dev for the example
pnpm next dev examples/basic
All examples are built with Next.js, so Next.js commands are all supported:
# if you want to build and start
pnpm next build examples/basic
pnpm next start examples/basic
Also note: Could not capture pnpm-lock.yaml: source unavailable or larger than the capture limit. Open its source link to check setup.