{"name":"swr","version":"0.4.3-beta.2","license":"MIT","_id":"swr@0.4.3-beta.2","maintainers":[{"name":"ernestd","email":"lapapelera@gmail.com"},{"name":"chriswdmr","email":"github.wolle404@gmail.com"},{"name":"cl3arglass","email":"haltaffer@gmail.com"},{"name":"divmain","email":"dale@divmain.com"},{"name":"sokra","email":"tobias.koppers@googlemail.com"},{"name":"raunofreiberg","email":"freiberggg@gmail.com"},{"name":"rizbizkits","email":"rizwana.akmal@hotmail.com"},{"name":"julianbenegas","email":"julianbenegas99@gmail.com"},{"name":"codetheory","email":"thecodetheory@gmail.com"},{"name":"matheuss","email":"matheus.frndes@gmail.com"},{"name":"igorklopov","email":"igor@klopov.com"},{"name":"leo","email":"mindrun@icloud.com"},{"name":"nkzawa","email":"naoyuki.kanezawa@gmail.com"},{"name":"tootallnate","email":"nathan@tootallnate.net"},{"name":"rauchg","email":"rauchg@gmail.com"},{"name":"timneutkens","email":"tim@timneutkens.nl"},{"name":"javivelasco","email":"javier.velasco86@gmail.com"},{"name":"iamevilrabbit","email":"hello@evilrabb.it"},{"name":"joecohens","email":"joecohenr@gmail.com"},{"name":"quietshu","email":"ds303077135@gmail.com"},{"name":"dav-is","email":"mail@connordav.is"},{"name":"juancampa","email":"juancampa@gmail.com"},{"name":"styfle","email":"steven@ceriously.com"},{"name":"zeit-bot","email":"team@zeit.co"},{"name":"lucleray","email":"luc.leray@gmail.com"},{"name":"mglagola","email":"mark.glagola@gmail.com"},{"name":"andybitz","email":"artzbitz@gmail.com"},{"name":"paulogdm","email":"paulogdemitri@gmail.com"},{"name":"anatrajkovska","email":"ana.trajkovska2015@gmail.com"},{"name":"timer","email":"timer150@gmail.com"},{"name":"umegaya","email":"iyatomi@gmail.com"},{"name":"arzafran","email":"franco@studiofreight.com"},{"name":"ijjk","email":"jj@jjsweb.site"},{"name":"mfix22","email":"mrfix84@gmail.com"},{"name":"lfades","email":"luisito453@gmail.com"},{"name":"rabaut","email":"rabautse@gmail.com"},{"name":"coetry","email":"allenhai03@gmail.com"},{"name":"msweeneydev","email":"mail@msweeneydev.com"},{"name":"williamli","email":"williamli@bbi.io"},{"name":"ragojose","email":"ragojosefrancisco@gmail.com"},{"name":"guybedford","email":"guybedford@gmail.com"},{"name":"paco","email":"pvco.coursey@gmail.com"},{"name":"skllcrn","email":"skllcrn@zeit.co"},{"name":"janicklas-ralph","email":"janicklasralph036@gmail.com"},{"name":"atcastle","email":"atcastle@gmail.com"},{"name":"keanulee","email":"npm@keanulee.com"},{"name":"spanicker","email":"shubhie@gmail.com"},{"name":"developit","email":"jason@developit.ca"},{"name":"housseindjirdeh","email":"houssein.djirdeh@gmail.com"},{"name":"gmonaco","email":"gbmonaco@google.com"},{"name":"kikobeats","email":"josefrancisco.verdu@gmail.com"},{"name":"prateekbh","email":"prateek89born@gmail.com"},{"name":"jkrems","email":"jan.krems@gmail.com"},{"name":"jaredpalmer","email":"jared@palmer.net"},{"name":"gielcobben","email":"g.cobben@gmail.com"},{"name":"chibicode","email":"shu@chibicode.com"},{"name":"nazarenooviedo","email":"nazareno@basement.studio"},{"name":"cleishm","email":"chris@leishman.org"},{"name":"samsisle","email":"samko9522@gmail.com"},{"name":"okbel","email":"curciobel@gmail.com"},{"name":"hankvercel","email":"hank@vercel.com"},{"name":"leerobinson","email":"lrobinson2011@gmail.com"},{"name":"elsigh","email":"lsimon@commoner.com"}],"homepage":"https://swr.vercel.app","bugs":{"url":"https://github.com/vercel/swr/issues"},"dist":{"shasum":"6cf9298fb67f8cd8c11bfe78ebffb54632fb350b","tarball":"http://registry-npm.ywwl.com/swr/download/swr-0.4.3-beta.2.tgz","fileCount":31,"integrity":"sha512-0+hF4OW2vMJkPm5sCok7QzOElIXWtLsgmaQwQkcGVEdkWj0wmUwDjaM3D7Az+6mDQYivIxY66y1yYjijNlQQMA==","signatures":[{"sig":"MEUCIQCICjGNiRE72y5BRpDVEqYSmrMw/gdPjQrT/bJk2T7KcAIgON1bZiRwpaq3mQncXg4hhNM8mA/EdxrGT/YnImv2o7I=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":108359,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgQ5G0CRA9TVsSAnZWagAAW60P/3JXp6PkOJhkYgF8L+7R\nMEolHyt6ClCpBCld8iECrH/h9vecknpSjHk0XU43DRRf7Z9kZwVDq+UAX2JP\nxaVBsiR9k51TCoAK7yRQLXkbHGWksTDN8GQLPlHlVxxOXSLqtzGVRPQRyCE8\npS2dO8IilTdnRcUg3wM3OK/DMC0wuEBlRZg+nr6hewmRm9lufwGbNMMAk/bs\nb++KI9JKV/tfgkkJhuYTgdmF5Fy1d7LSWT5wzc5ploj3Z/PORR8jNvzlZ+tQ\nsvdQfRNOwg7ISb5nrclROCR/DbcSupVD7GY3tLVb1ZPfNY4FCA3P4WYo6qSs\nkcbb/hZPkT0mIm7dVTdyaC/eYw2PiIRIr/AFBjmHdeLapp9tTalpdjAcKRy9\ndWvg/34gaZrSxjaDMEhBDrjj4mSACGfSqCbk2/UmVYlVT1AOM9hKz6V+MOqM\nQK6GxzEdazxcjH/S6ZBP7VuHUCO/1mz+kHfRvDaCHEcqZgWbOmN3xmPp7qCi\nEyQTJuHkxD+zvi0vz5M3MgsblmJq6BeivYYTEmNJVmnLfV+CCgTmzUZPJ2K/\ndGS4x3mt95xAX6VSARsMnB77xYT8+b/nqLZ9tRLUIlNwL6L7xKKR1MDZ+tkN\nZyBH0WWjdOiR6PFjCYjJCcLAsRO+qO127Bx0NvEmrPyftwEPD8kwZre1GHjJ\nO2+w\r\n=8lRL\r\n-----END PGP SIGNATURE-----\r\n","size":27136,"noattachment":false,"key":"/swr/-/swr-0.4.3-beta.2.tgz"},"main":"./dist/index.js","husky":{"hooks":{"pre-commit":"npm run types:check && lint-staged"}},"types":"./dist/index.d.ts","module":"./esm/index.js","readme":"[![SWR](https://assets.vercel.com/image/upload/v1572289618/swr/banner.png)](https://swr.vercel.app)\n\n<p align=\"center\">\n\n  <a aria-label=\"Vercel logo\" href=\"https://vercel.com\">\n    <img src=\"https://badgen.net/badge/icon/Made%20by%20Vercel?icon=zeit&label&color=black&labelColor=black\">\n  </a>\n  <br/>\n\n  <a aria-label=\"NPM version\" href=\"https://www.npmjs.com/package/swr\">\n    <img alt=\"\" src=\"https://badgen.net/npm/v/swr\">\n  </a>\n  <a aria-label=\"Package size\" href=\"https://bundlephobia.com/result?p=swr\">\n    <img alt=\"\" src=\"https://badgen.net/bundlephobia/minzip/swr\">\n  </a>\n  <a aria-label=\"License\" href=\"https://github.com/zeit/swr/blob/master/LICENSE\">\n    <img alt=\"\" src=\"https://badgen.net/npm/license/swr\">\n  </a>\n</p>\n\n## Introduction\n\n[swr.vercel.app](https://swr.vercel.app)\n\nSWR is a React Hooks library for remote data fetching.\n\nThe name “**SWR**” is derived from `stale-while-revalidate`, a cache invalidation strategy popularized by [HTTP RFC 5861](https://tools.ietf.org/html/rfc5861).\n**SWR** first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.\n\nIt features:\n\n- Transport and protocol agnostic data fetching\n- Fast page navigation\n- Revalidation on focus\n- Interval polling\n- Request deduplication\n- Local mutation\n- Pagination\n- TypeScript ready\n- SSR support\n- Suspense mode\n- React Native support\n- Minimal API\n\n...and a lot more.\n\nWith SWR, components will get **a stream of data updates constantly and automatically**. Thus, the UI will be always **fast** and **reactive**.\n\n<br/>\n\n## Quick Start\n\n```js\nimport useSWR from 'swr'\n\nfunction Profile() {\n  const { data, error } = useSWR('/api/user', fetcher)\n\n  if (error) return <div>failed to load</div>\n  if (!data) return <div>loading...</div>\n  return <div>hello {data.name}!</div>\n}\n```\n\nIn this example, the React Hook `useSWR` accepts a `key` and a `fetcher` function.\nThe `key` is a unique identifier of the request, normally the URL of the API. And the `fetcher` accepts\n`key` as its parameter and returns the data asynchronously.\n\n`useSWR` also returns 2 values: `data` and `error`. When the request (fetcher) is not yet finished,\n`data` will be `undefined`. And when we get a response, it sets `data` and `error` based on the result\nof `fetcher` and rerenders the component.\n\nNote that `fetcher` can be any asynchronous function, so you can use your favourite data-fetching\nlibrary to handle that part.\n\nCheck out [swr.vercel.app](https://swr.vercel.app) for more demos of SWR, and [Examples](#examples) for the best practices.\n\n<br/>\n\n## Usage\n\nInside your React project directory, run the following:\n\n```\nyarn add swr\n```\n\nOr with npm:\n\n```\nnpm install swr\n```\n\n### API\n\n```js\nconst { data, error, isValidating, mutate } = useSWR(key, fetcher, options)\n```\n\n#### Parameters\n\n- `key`: a unique key string for the request (or a function / array / null) [(advanced usage)](#conditional-fetching)\n- `fetcher`: (_optional_) a Promise returning function to fetch your data [(details)](#data-fetching)\n- `options`: (_optional_) an object of options for this SWR hook\n\n#### Return Values\n\n- `data`: data for the given key resolved by `fetcher` (or undefined if not loaded)\n- `error`: error thrown by `fetcher` (or undefined)\n- `isValidating`: if there's a request or revalidation loading\n- `mutate(data?, shouldRevalidate?)`: function to mutate the cached data\n\n#### Options\n\n- `suspense = false`: enable React Suspense mode [(details)](#suspense-mode)\n- `fetcher = window.fetch`: the default fetcher function\n- `initialData`: initial data to be returned (note: This is per-hook)\n- `revalidateOnMount`: enable or disable automatic revalidation when component is mounted (by default revalidation occurs on mount when initialData is not set, use this flag to force behavior)\n- `revalidateOnFocus = true`: auto revalidate when window gets focused\n- `revalidateOnReconnect = true`: automatically revalidate when the browser regains a network connection (via `navigator.onLine`)\n- `refreshInterval = 0`: polling interval (disabled by default)\n- `refreshWhenHidden = false`: polling when the window is invisible (if `refreshInterval` is enabled)\n- `refreshWhenOffline = false`: polling when the browser is offline (determined by `navigator.onLine`)\n- `shouldRetryOnError = true`: retry when fetcher has an error [(details)](#error-retries)\n- `dedupingInterval = 2000`: dedupe requests with the same key in this time span\n- `focusThrottleInterval = 5000`: only revalidate once during a time span\n- `loadingTimeout = 3000`: timeout to trigger the onLoadingSlow event\n- `errorRetryInterval = 5000`: error retry interval [(details)](#error-retries)\n- `errorRetryCount`: max error retry count [(details)](#error-retries)\n- `onLoadingSlow(key, config)`: callback function when a request takes too long to load (see `loadingTimeout`)\n- `onSuccess(data, key, config)`: callback function when a request finishes successfully\n- `onError(err, key, config)`: callback function when a request returns an error\n- `onErrorRetry(err, key, config, revalidate, revalidateOps)`: handler for [error retry](#error-retries)\n- `compare(a, b)`: comparison function used to detect when returned data has changed, to avoid spurious rerenders. By default, [`dequal/lite`](https://github.com/lukeed/dequal) is used.\n- `isPaused()`: function to detect whether pause revalidations, will ignore fetched data and errors when it returns `true`. Returns `false` by default.\n\nWhen under a slow network (2G, <= 70Kbps), `errorRetryInterval` will be 10s, and\n`loadingTimeout` will be 5s by default.\n\nYou can also use a [global configuration](#global-configuration) to provide default options.\n\n<br/>\n\n## Examples\n\n- [Global Configuration](#global-configuration)\n- [Data Fetching](#data-fetching)\n- [Conditional Fetching](#conditional-fetching)\n- [Dependent Fetching](#dependent-fetching)\n- [Multiple Arguments](#multiple-arguments)\n- [Manually Revalidate](#manually-revalidate)\n- [Mutation and Post Request](#mutation-and-post-request)\n- [Mutate Based on Current Data](#mutate-based-on-current-data)\n- [Returned Data from Mutate](#returned-data-from-mutate)\n- [SSR with Next.js](#ssr-with-nextjs)\n- [Suspense Mode](#suspense-mode)\n- [Error Retries](#error-retries)\n- [Prefetching Data](#prefetching-data)\n- [Request Deduplication](#request-deduplication)\n\n### Global Configuration\n\nThe context `SWRConfig` can provide global configurations (`options`) for all SWR hooks.\n\nIn this example, all SWRs will use the same fetcher provided to load JSON data, and refresh every 3 seconds by default:\n\n```js\nimport useSWR, { SWRConfig } from 'swr'\n\nfunction Dashboard() {\n  const { data: events } = useSWR('/api/events')\n  const { data: projects } = useSWR('/api/projects')\n  const { data: user } = useSWR('/api/user', { refreshInterval: 0 }) // don't refresh\n  // ...\n}\n\nfunction App() {\n  return (\n    <SWRConfig\n      value={{\n        refreshInterval: 3000,\n        fetcher: (...args) => fetch(...args).then(res => res.json())\n      }}\n    >\n      <Dashboard />\n    </SWRConfig>\n  )\n}\n```\n\n### Data Fetching\n\n`fetcher` is a function that **accepts the `key`** of SWR, and returns a value or a Promise.\nYou can use any library to handle data fetching, for example:\n\n```js\nimport fetch from 'unfetch'\n\nconst fetcher = url => fetch(url).then(r => r.json())\n\nfunction App() {\n  const { data } = useSWR('/api/data', fetcher)\n  // ...\n}\n```\n\nOr using GraphQL:\n\n```js\nimport { request } from 'graphql-request'\n\nconst fetcher = query => request('/api/graphql', query)\n\nfunction App() {\n  const { data, error } = useSWR(\n    `{\n      Movie(title: \"Inception\") {\n        releaseDate\n        actors {\n          name\n        }\n      }\n    }`,\n    fetcher\n  )\n  // ...\n}\n```\n\n_If you want to pass variables to a GraphQL query, check out [Multiple Arguments](#multiple-arguments)._\n\nNote that `fetcher` can be omitted from the parameters if it's provided globally.\n\n### Conditional Fetching\n\nUse `null` or pass a function as the `key` to `useSWR` to conditionally fetch data. If the functions throws an error or returns a falsy value, SWR will cancel the request.\n\n```js\n// conditionally fetch\nconst { data } = useSWR(shouldFetch ? '/api/data' : null, fetcher)\n\n// ...or return a falsy value\nconst { data } = useSWR(() => shouldFetch ? '/api/data' : null, fetcher)\n\n// ... or throw an error when user.id is not defined\nconst { data } = useSWR(() => '/api/data?uid=' + user.id, fetcher)\n```\n\n### Dependent Fetching\n\nSWR also allows you to fetch data that depends on other data. It ensures the maximum possible parallelism (avoiding waterfalls), as well as serial fetching when a piece of dynamic data is required for the next data fetch to happen.\n\n```js\nfunction MyProjects() {\n  const { data: user } = useSWR('/api/user')\n  const { data: projects } = useSWR(() => '/api/projects?uid=' + user.id)\n  // When passing a function, SWR will use the return\n  // value as `key`. If the function throws or returns\n  // falsy, SWR will know that some dependencies are not\n  // ready. In this case `user.id` throws when `user`\n  // isn't loaded.\n\n  if (!projects) return 'loading...'\n  return 'You have ' + projects.length + ' projects'\n}\n```\n\n### Multiple Arguments\n\nIn some scenarios, it's useful to pass multiple arguments (can be any value or object) to the `fetcher` function. For example:\n\n```js\nuseSWR('/api/user', url => fetchWithToken(url, token))\n```\n\nThis is **incorrect**. Because the identifier (also the index of the cache) of the data is `'/api/user'`,\nso even if `token` changes, SWR will still have the same key and return the wrong data.\n\nInstead, you can use an **array** as the `key` parameter, which contains multiple arguments of `fetcher`:\n\n```js\nconst { data: user } = useSWR(['/api/user', token], fetchWithToken)\n\n// ...and pass it as an argument to another query\nconst { data: orders } = useSWR(user ? ['/api/orders', user] : null, fetchWithUser)\n```\n\nThe key of the request is now the combination of both values. SWR **shallowly** compares\nthe arguments on every render and triggers revalidation if any of them has changed.\nKeep in mind that you should not recreate objects when rendering, as they will be treated as different objects on every render:\n\n```js\n// Don’t do this! Deps will be changed on every render.\nuseSWR(['/api/user', { id }], query)\n\n// Instead, you should only pass “stable” values.\nuseSWR(['/api/user', id], (url, id) => query(url, { id }))\n```\n\nDan Abramov explains dependencies very well in [this blog post](https://overreacted.io/a-complete-guide-to-useeffect/#but-i-cant-put-this-function-inside-an-effect).\n\n### Manually Revalidate\n\nYou can broadcast a revalidation message globally to all SWRs with the same key by calling\n`mutate(key)`.\n\nThis example shows how to automatically refetch the login info (e.g.: inside `<Profile/>`)\nwhen the user clicks the “Logout” button.\n\n```js\nimport useSWR, { mutate } from 'swr'\n\nfunction App() {\n  return (\n    <div>\n      <Profile />\n      <button onClick={() => {\n        // set the cookie as expired\n        document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'\n\n        // tell all SWRs with this key to revalidate\n        mutate('/api/user')\n      }}>\n        Logout\n      </button>\n    </div>\n  )\n}\n```\n\n### Mutation and Post Request\n\nIn many cases, applying local mutations to data is a good way to make changes\nfeel faster — no need to wait for the remote source of data.\n\nWith `mutate`, you can update your local data programmatically, while\nrevalidating and finally replace it with the latest data.\n\n```js\nimport useSWR, { mutate } from 'swr'\n\nfunction Profile() {\n  const { data } = useSWR('/api/user', fetcher)\n\n  return (\n    <div>\n      <h1>My name is {data.name}.</h1>\n      <button onClick={async () => {\n        const newName = data.name.toUpperCase()\n        \n        // update the local data immediately, but disable the revalidation\n        mutate('/api/user', { ...data, name: newName }, false)\n        \n        // send a request to the API to update the source\n        await requestUpdateUsername(newName)\n        \n        // trigger a revalidation (refetch) to make sure our local data is correct\n        mutate('/api/user')\n      }}>Uppercase my name!</button>\n    </div>\n  )\n}\n```\n\nClicking the button in the example above will send a POST request to modify the remote data, locally update the client data and\ntry to fetch the latest one (revalidate).\n\nBut many POST APIs will just return the updated data directly, so we don’t need to revalidate again.\nHere’s an example showing the “local mutate - request - update” usage:\n\n```js\nmutate('/api/user', newUser, false)      // use `false` to mutate without revalidation\nmutate('/api/user', updateUser(newUser)) // `updateUser` is a Promise of the request,\n                                         // which returns the updated document\n```\n\n### Mutate Based on Current Data\n\nIn many cases, you are receiving a single value back from your API and want to update a list of them.\n\nWith `mutate`, you can pass an async function which will receive the current cached value, if any, and let you return an updated document.\n\n```js\nmutate('/api/users', async users => {\n  const user = await fetcher('/api/users/1')\n  return [user, ...users.slice(1)]\n})\n```\n\n### Returned Data from Mutate\n\nMost probably, you need some data to update the cache. The data is resolved or returned from the promise or async function you passed to `mutate`.\n\nThe function will return an updated document to let `mutate` update the corresponding cache value. It could throw an error somehow, every time when you call it.\n\n```js\ntry {\n  const user = await mutate('/api/user', updateUser(newUser))\n} catch (error) {\n  // Handle an error while updating the user here\n}\n```\n\n### Bound `mutate()`\n\nThe SWR object returned by `useSWR` also contains a `mutate()` function that is pre-bound to the SWR's key.\n\nIt is functionally equivalent to the global `mutate` function but does not require the `key` parameter.\n\n```js\nimport useSWR from 'swr'\n\nfunction Profile() {\n  const { data, mutate } = useSWR('/api/user', fetcher)\n\n  return (\n    <div>\n      <h1>My name is {data.name}.</h1>\n      <button onClick={async () => {\n        const newName = data.name.toUpperCase()\n        // send a request to the API to update the data\n        await requestUpdateUsername(newName)\n        // update the local data immediately and revalidate (refetch)\n        // NOTE: key is not required when using useSWR's mutate as it's pre-bound\n        mutate({ ...data, name: newName })\n      }}>Uppercase my name!</button>\n    </div>\n  )\n}\n```\n\n### SSR with Next.js\n\nWith the `initialData` option, you pass an initial value to the hook. It works perfectly with many SSR solutions\nsuch as `getServerSideProps` in [Next.js](https://github.com/zeit/next.js):\n\n```js\nexport async function getServerSideProps() {\n  const data = await fetcher('/api/data')\n  return { props: { data } }\n}\n\nfunction App(props) {\n  const initialData = props.data\n  const { data } = useSWR('/api/data', fetcher, { initialData })\n\n  return <div>{data}</div>\n}\n```\n\nIt is still a server-side rendered site, but it’s also fully powered by SWR in the client-side.\nWhich means the data can be dynamic and update itself over time and user interactions.\n\n### Suspense Mode\n\nYou can enable the `suspense` option to use SWR with React Suspense:\n\n```js\nimport { Suspense } from 'react'\nimport useSWR from 'swr'\n\nfunction Profile() {\n  const { data } = useSWR('/api/user', fetcher, { suspense: true })\n  return <div>hello, {data.name}</div>\n}\n\nfunction App() {\n  return (\n    <Suspense fallback={<div>loading...</div>}>\n      <Profile/>\n    </Suspense>\n  )\n}\n```\n\nIn Suspense mode, `data` is always the fetch response (so you don't need to check if it's `undefined`).\nBut if an error occurred, you need to use an [error boundary](https://reactjs.org/docs/concurrent-mode-suspense.html#handling-errors) to catch it.\n\n_Note that Suspense is not supported in SSR mode._\n\n### Error Retries\n\nBy default, SWR uses the [exponential backoff algorithm](https://en.wikipedia.org/wiki/Exponential_backoff) to handle error retries.\nYou can read more from the source code.\n\nIt's also possible to override the behavior:\n\n```js\nuseSWR(key, fetcher, {\n  onErrorRetry: (error, key, option, revalidate, { retryCount }) => {\n    if (retryCount >= 10) return\n    if (error.status === 404) return\n\n    // retry after 5 seconds\n    setTimeout(() => revalidate({ retryCount: retryCount + 1 }), 5000)\n  }\n})\n```\n\n### Prefetching Data\n\nThere’re many ways to prefetch the data for SWR. For top-level requests, [`rel=\"preload\"`](https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content) is highly recommended:\n\n```html\n<link rel=\"preload\" href=\"/api/data\" as=\"fetch\" crossorigin=\"anonymous\">\n```\n\nThis will prefetch the data before the JavaScript starts downloading. And your incoming fetch requests will reuse the result (including SWR, of course).\n\nAnother choice is to prefetch the data conditionally. You can have a function to refetch and set the cache:\n\n```js\nfunction prefetch() {\n  mutate('/api/data', fetch('/api/data').then(res => res.json()))\n  // the second parameter is a Promise\n  // SWR will use the result when it resolves\n}\n```\n\nAnd use it when you need to preload the **resources** (for example when [hovering](https://github.com/GoogleChromeLabs/quicklink) [a](https://github.com/guess-js/guess) [link](https://instant.page)).\nTogether with techniques like [page prefetching](https://nextjs.org/docs#prefetching-pages) in Next.js, you will be able to load both next page and data instantly.\n\n### Request Deduplication\n\nSWR deduplicates requests by default. If you call the hook with the same key multiple times, only one request is made. Duplicated calls will receive a value from cache.\nHere, the 'api/user' key is used in two requests:\n\n```js\nimport useSWR from 'swr'\n\nfunction UserProfileName() {\n  const { data, error } = useSWR('/api/user', fetcher)\n\n  if (error) return <div>failed to load</div>\n  if (!data) return <div>loading...</div>\n  return <p>Name: {data.name}!</p>\n}\n\nfunction UserProfileAvatar() {\n  const { data, error } = useSWR('/api/user', fetcher)\n\n  if (error) return <div>failed to load</div>\n  if (!data) return <div>loading...</div>\n  return <img src={data.avatarUrl} alt=\"Profile image\" />\n}\n\nexport default function App() {\n  return (\n    <div>\n      <UserProfileName />\n      <UserProfileAvatar />\n    </div>\n  )\n}\n```\n\nBy default, requests made within 2 seconds are deduped. This can be changed by setting the `dedupingInterval` option:\n\n```js\nconst { data, error } = useSWR('/api/user', fetcher, { dedupingInterval: 1000 })\n```\n\nThis will deduplicate requests at an interval of 1 second.\n<br/>\n\n## Authors\n\n- Shu Ding ([@shuding_](https://twitter.com/shuding_)) – [Vercel](https://vercel.com)\n- Guillermo Rauch ([@rauchg](https://twitter.com/rauchg)) – [Vercel](https://vercel.com)\n- Joe Haddad ([@timer150](https://twitter.com/timer150)) - [Vercel](https://vercel.com)\n- Paco Coursey ([@pacocoursey](https://twitter.com/pacocoursey)) - [Vercel](https://vercel.com)\n\nThanks to Ryan Chen for providing the awesome `swr` npm package name!\n\n<br/>\n\n## License\n\nThe MIT License.\n","gitHead":"cb4ee96659ec943f76069a5849674ba0aad291e5","scripts":{"lint":"eslint \"{src,test,examples}/**/*.{ts,tsx}\"","test":"jest","build":"npm run build:esm && npm run build:cjs","watch":"tsc --watch","format":"prettier --write \"{src,test,examples}/**/*.{ts,tsx}\"","dev:next":"concurrently \"yarn watch:esm\" \"cd playground/next-swr && yarn dev\"","dev:vite":"concurrently \"yarn watch:esm\" \"cd playground/vite-swr && yarn dev\"","lint:fix":"eslint \"{src,test,examples}/**/*.{ts,tsx}\" --fix","register":"yarn link && cd node_modules/react && yarn link","build:cjs":"ncc build src/index.ts -o dist -m -e react","build:esm":"tsc --module ES6 --outDir esm","watch:esm":"tsc --module ES6 --outDir esm --target esnext --watch","types:check":"tsc --noEmit","prepare:next":"git clone https://github.com/promer94/next-swr playground/next-swr && cd playground/next-swr && yarn && yarn link react && yarn link swr","prepare:vite":"git clone https://github.com/promer94/vite-swr playground/vite-swr && cd playground/vite-swr && yarn && yarn link react && yarn link swr"},"_npmUser":{"name":"quietshu","email":"ds303077135@gmail.com"},"repository":{"url":"git+https://github.com/vercel/swr.git","type":"git"},"_npmVersion":"6.14.4","description":"React Hooks library for remote data fetching","directories":{},"lint-staged":{"*.{ts,tsx}":["npm run lint:fix","npm run format","git add"]},"_nodeVersion":"12.18.0","dependencies":{"dequal":"2.0.2"},"react-native":"./esm/index.js","_hasShrinkwrap":false,"readmeFilename":"README.md","devDependencies":{"jest":"25.5.4","husky":"2.4.1","react":"16.11.0","eslint":"6.6.0","ts-jest":"25.5.1","prettier":"1.18.2","@zeit/ncc":"0.20.5","react-dom":"16.11.0","typescript":"3.6.4","@types/jest":"25.2.3","@types/node":"11.12.0","lint-staged":"8.2.1","@types/react":"16.9.11","concurrently":"6.0.0","eslint-plugin-react":"7.20.6","@testing-library/react":"10.1.0","eslint-config-prettier":"6.5.0","eslint-plugin-jest-dom":"3.6.5","@testing-library/jest-dom":"5.11.9","@typescript-eslint/parser":"2.5.0","eslint-plugin-react-hooks":"4.1.2","eslint-plugin-testing-library":"3.10.1","@typescript-eslint/eslint-plugin":"2.5.0"},"peerDependencies":{"react":"^16.11.0 || ^17.0.0"},"_npmOperationalInternal":{"tmp":"tmp/swr_0.4.3-beta.2_1615040947962_0.004156442316024078","host":"s3://npm-registry-packages"},"publish_time":1615040948151,"_cnpm_publish_time":1615040948151,"dist-tags":{"beta":"2.6.0-beta.0","latest":"2.5.1","rc":"2.0.0-rc.3"}}