{"_id":"@aboulman/swr","_rev":"1-5b0b0f5513bdb7ba6e3ddc1bb9b0fef8","name":"@aboulman/swr","dist-tags":{"latest":"0.1.15"},"versions":{"0.1.15":{"name":"@aboulman/swr","version":"0.1.15","description":"React Hooks library for remote data fetching","main":"./dist/index.js","module":"./esm/index.js","react-native":"./esm/index.js","types":"./dist/index.d.ts","repository":{"type":"git","url":"git+https://github.com/zeit/swr.git"},"homepage":"https://swr.now.sh","license":"MIT","scripts":{"dev":"now dev","build":"npm run build:esm && npm run build:cjs","build:cjs":"ncc build src/index.ts -o dist -m -e react","build:esm":"tsc --target ESNext --module ES6 --outDir esm","watch":"tsc --watch","types:check":"tsc --noEmit","format":"prettier --write \"{src,test,examples}/**/*.{ts,tsx}\"","lint":"eslint \"{src,test,examples}/**/*.{ts,tsx}\"","lint:fix":"eslint \"{src,test,examples}/**/*.{ts,tsx}\" --fix","test":"jest"},"husky":{"hooks":{"pre-commit":"npm run types:check && lint-staged"}},"lint-staged":{"*.{ts,tsx}":["npm run lint:fix","npm run format","git add"]},"devDependencies":{"@testing-library/react":"9.3.0","@types/jest":"24.0.20","@types/node":"11.12.0","@types/react":"16.9.11","@typescript-eslint/eslint-plugin":"2.5.0","@typescript-eslint/parser":"2.5.0","@zeit/ncc":"0.20.5","eslint":"6.6.0","eslint-config-prettier":"6.5.0","husky":"2.4.1","jest":"24.9.0","lint-staged":"8.2.1","prettier":"1.18.2","react":"16.11.0","react-dom":"16.11.0","ts-jest":"24.1.0","typescript":"3.6.4"},"dependencies":{"fast-deep-equal":"2.0.1"},"peerDependencies":{"react":"^16.11.0"},"gitHead":"4d5e8bc8b932f7301dad2e801bfb93f03d120e3f","bugs":{"url":"https://github.com/zeit/swr/issues"},"_id":"@aboulman/swr@0.1.15","_npmVersion":"6.4.1","_nodeVersion":"10.15.3","_npmUser":{"name":"aboulmane","email":"anassboulmane@gmail.com"},"dist":{"integrity":"sha512-FjIJBWglWd7MQvEa007W23PZiXq1YUwFwLyPY9cEM//ci0zKR0LT0sQYfD1yvKT3w4OnUnFXMhsAbDjbeM8CJA==","shasum":"43d0060f6c4ea4ecf2b0c253bfc37b462f142e61","tarball":"https://registry.npmjs.org/@aboulman/swr/-/swr-0.1.15.tgz","fileCount":37,"unpackedSize":68256,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJd+TnLCRA9TVsSAnZWagAA9yoP/1yhKeBnzWhlQV6csiY3\nzQAoExhs2g2AODpl/N0rHqRku6h/Oz9fFzjUq1qGDPow3RrtLKqZeO/gKAIo\nLESzDJIks+i2amVhkiBTykEmuodynrujXb7wBh5JZSfS1YSwuOY1lZEKCYfs\nhJpVwV1erLkC4KXduj/2nZQpbtDXjuBomEefwWha9vRx21WLnzXJjFiUGZnz\nPONaQi6+GrQgBDeDYzpS5W/WyfD630daSVoMDpIOGb/Xkd8ve28xH+voAvDu\nX0ykgRR9Ywnt/XGNXRu/HvQiLKZat21nmi7CPdIKz6sWEPa5pAkbVv/p+xDg\n9pVo/C/e7o3I3kRE2aMeOJ/lWUV+apzC2/pq/orB6uykMcJ/J8/jbCQZWHbb\n0CyAVZVxd9XikFK6dEM6NtdeQ0j11e+HWopwV7Bak9gQM84Lm1YeG0biIOPF\n8XwzJGLqEcUIqCmq/BdRt3hUq4u7XfScpIw6/vnoQS9YkSNlhFY3M9nJGp0O\nXCiEev9vdvVKNIvVZv56v+L5kfbBYDaM56K5IO27jTOGEoxL6TEb5kOwvCik\n+bDQWymmvBuiqDn77aub9BwOlitbnTSbS6pF6iD/l5k2SUTQVS7Z6T+iFpgd\nzkhWYjf+GaNi6tU8QWS/gchLvxUEwIhgwEJ3yU0sIM7hdxVhPpHN/ly+0002\niTVg\r\n=YjBo\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIFxQqav3GkNK6x/WQo+jLxywPRnQN4/XbWVm5UPORnxMAiEA2t4vUJobskN531WCtpv6a0j+akiJXQ5tSaqQLjQf1H4="}]},"maintainers":[{"name":"aboulmane","email":"anassboulmane@gmail.com"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/swr_0.1.15_1576614347501_0.21930157273052098"},"_hasShrinkwrap":false}},"time":{"created":"2019-12-17T20:25:47.269Z","0.1.15":"2019-12-17T20:25:47.650Z","modified":"2022-04-04T11:00:18.104Z"},"maintainers":[{"name":"aboulmane","email":"anassboulmane@gmail.com"}],"description":"React Hooks library for remote data fetching","homepage":"https://swr.now.sh","repository":{"type":"git","url":"git+https://github.com/zeit/swr.git"},"bugs":{"url":"https://github.com/zeit/swr/issues"},"license":"MIT","readme":"[![SWR](https://assets.zeit.co/image/upload/v1572289618/swr/banner.png)](https://swr.now.sh)\n\n<p align=\"center\">\n  <a aria-label=\"ZEIT logo\" href=\"https://github.com/zeit\">\n    <img src=\"https://badgen.net/badge/icon/MADE%20BY%20ZEIT?icon=zeit&label&color=black&labelColor=black\">\n  </a>\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.now.sh](https://swr.now.sh)\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- Transport and protocol agnostic data fetching\n- Fast page navigation\n- Revalidation on focus\n- Interval polling\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.\n`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.now.sh](https://swr.now.sh) 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, revalidate } = 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- `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- `revalidate`: function to trigger the validation manually\n\n#### Options\n\n- `suspense = false`: enable React Suspense mode [(details)](#suspense-mode)\n- `fetcher = undefined`: the default fetcher function\n- `initialData`: initial data to be returned (note: This is per-hook)\n- `revalidateOnFocus = true`: auto revalidate when window gets focused\n- `refreshInterval = 0`: polling interval (disabled by default)\n- `refreshWhenHidden = false`: polling when the window is invisible (if `refreshInterval` is enabled)\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- `onLoadingSlow`: callback function when a request takes too long to load (see `loadingTimeout`)\n- `onSuccess`: callback function when a request finishes successfully\n- `onError`: callback function when a request returns an error\n- `onErrorRetry`: handler for [error retry](#error-retries)\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 [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- [SSR with Next.js](#ssr-with-nextjs)\n- [Suspense Mode](#suspense-mode)\n- [Error Retries](#error-retries)\n- [Prefetching Data](#prefetching-data)\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```js\nimport { request } from 'graphql-request'\n\nconst API = 'https://api.graph.cool/simple/v1/movies'\nconst fetcher = query => request(API, 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\n  // return value as `key`. If the function throws,\n  // SWR will know that some dependencies are not\n  // ready. In this case it is `user`.\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 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/data'`, \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`trigger(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, { trigger } 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        trigger('/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        // send a request to the API to update the data\n        await requestUpdateUsername(newName)\n        // update the local data immediately and revalidate (refetch)\n        mutate('/api/user', { ...data, name: newName })\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### 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 `getInitialProps` in [Next.js](https://github.com/zeit/next.js):\n\n```js\nApp.getInitialProps = async () => {\n  const data = await fetcher('/api/data')\n  return { 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<br/>\n\n## Authors\n- Shu Ding ([@shuding_](https://twitter.com/shuding_)) – [ZEIT](https://zeit.co)\n- Guillermo Rauch ([@rauchg](https://twitter.com/rauchg)) – [ZEIT](https://zeit.co)\n- Joe Haddad ([@timer150](https://twitter.com/timer150)) - [ZEIT](https://zeit.co)\n- Paco Coursey ([@pacocoursey](https://twitter.com/pacocoursey)) - [ZEIT](https://zeit.co)\n\nThanks to Ryan Chen for providing the awesome `swr` npm package name!\n\n<br/>\n\n## License\nThe MIT License.\n","readmeFilename":"README.md"}