{"dist":{"shasum":"7be7d29251e0539a4c1a8693c01d0f9aa802848d","tarball":"https://registry.npmjs.org/react-query/-/react-query-0.1.1-alpha.0.tgz","fileCount":9,"integrity":"sha512-fODQUU0AA/p0SpaHDL41SjmMBUvVzjJP8XpxZfRljU/vizd3OdVGaLcQ1Gn9yVHnzbjwbJ0t6HsUA6Gdq/GDCg==","signatures":[{"sig":"MEUCIQDhH/XrWeUeTbM4wNvmyDw1GQKw0wr3L0xSD2XFVa5LNQIgehrPnAPPbdFH6woIZbYqSohueSG63sGx6Lqmlk/LCBY=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":174299,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdwLeVCRA9TVsSAnZWagAAs1EP/01RDn3DdmjDNE3fd9Fv\nVq7gaWmIDdLnwVWeOrmdPNcEONPf+rS9qBFvUeyIAWeEcNYLHCF4Gp7tCg2O\nojjQeK09bRe7JPSdsMcc4rXQk3LmoALxM1ZlYU0f5nszYcdUsM0+5q1+gFZk\nPfzRgb+fmWVjYwMuDWPufriNRbtLwGK7adHjfYN9fGaxO+/283575DZgMrWr\nJu4BQZxaxLHJzTlA4yIL5EZ3OJzZxwzeZ53bwm4cYec6lr6Wng1myFUsQWJO\nrBI61CeP55v/EVheNE/kBd4/fVVb3KAM9KbPYqPc1Pr//JYI855aHg67fyQX\nqlGMTW+Xd7GHOXvtvSJ1AWmnHlwVNJVpbBa8y401TrRmWYwM4/4GH+qCujCQ\nDQZReJP349/eaxZWUF7/sf3A3/UPQqW+o6hRAjOu3CSHIginU1oqvxjnrj9m\n+kiWtCgGkcyrgvDSZQW35VntsgZ+p5PHVhe18LZVSB5RCHcerMgt8duhDOfE\no2elOyilvvSftaHiJ6VZ/iSsCOaCU2Je8COCTkEbZ0rrvBKULp14jBn3zH4Y\nkl+3CZ97rrAC3TSIdFis6IaIu9L9JFOebWuI42aID53laecOwDUZUtvKw05l\n9aKonXhStomyjzIih4oPw1UQiM7wIJeNxcn2scxaiXmEnHy1Bb2h/1ro7e9q\nFhIo\r\n=dere\r\n-----END PGP SIGNATURE-----\r\n"},"main":"dist/index.js","name":"react-query","author":{"name":"tannerlinsley"},"module":"dist/index.es.js","readme":"![React Query Header](https://github.com/tannerlinsley/react-query/raw/master/media/header.png)\n\n<img src='https://github.com/tannerlinsley/react-query/raw/master/media/logo.png' width='300'/>\n\nHooks for fetching, caching and updating asynchronous data in React\n\n<!-- <a href=\"https://travis-ci.org/tannerlinsley/react-query\" target=\"\\_parent\">\n  <img alt=\"\" src=\"https://travis-ci.org/tannerlinsley/react-query.svg?branch=master\" />\n</a> -->\n<a href=\"https://npmjs.com/package/react-query\" target=\"\\_parent\">\n  <img alt=\"\" src=\"https://img.shields.io/npm/dm/react-query.svg\" />\n</a>\n<a href=\"https://bundlephobia.com/result?p=react-query@latest\" target=\"\\_parent\">\n  <img alt=\"\" src=\"https://badgen.net/bundlephobia/minzip/react-query@latest\" />\n</a>\n<a href=\"https://spectrum.chat/react-query\">\n  <img alt=\"Join the community on Spectrum\" src=\"https://withspectrum.github.io/badge/badge.svg\" />\n</a>\n<a href=\"https://github.com/tannerlinsley/react-query\" target=\"\\_parent\">\n  <img alt=\"\" src=\"https://img.shields.io/github/stars/tannerlinsley/react-query.svg?style=social&label=Star\" />\n</a>\n<a href=\"https://twitter.com/tannerlinsley\" target=\"\\_parent\">\n  <img alt=\"\" src=\"https://img.shields.io/twitter/follow/tannerlinsley.svg?style=social&label=Follow\" />\n</a>\n\n### [Become a Sponsor](https://github.com/sponsors/tannerlinsley)\n\n## Quick Features\n\n- Transport, protocol & backend agnostic data fetching\n- Auto Caching + Refetching (stale-while-revalidate, Window Refocus, Polling/Realtime)\n- Parallel + Dependent Queries\n- Mutations + Automatic Query Refetching\n- Multi-layer Cache + Garbage Collection\n- Load-More Pagination + Scroll Recovery\n- Suspense Support (Coming Soon)\n- 4.1 kb (minzipped)\n\n<details>\n<summary>Core Issues and Solution</summary>\n\n## The Challenge\n\nTools for managing async data and client stores/caches are plentiful these days, but most of these tools:\n\n- Duplicate unnecessary network operations\n- Force normalized or object/id-based caching strategies on your data\n- Do not automatically manage stale-ness or caching\n- Do not offer robust API's around mutation events, invalidation or query management\n- Are built for highly-opinionated systems like Redux, GraphQL, [insert proprietary tools] etc.\n\n## The Solution\n\nReact Query exports a set of hooks that attempt to address these issues. Out of the box, React Query:\n\n- Flexibly dedupes simultaneous requests to assets\n- Automatically caches data\n- Automatically invalidates stale cache data\n- Optimistically updates stale requests in the background\n- Automatically manages garbage collection\n- Supports automatic retries and exponential or custom back-off delays\n- Provides both declarative and imperative API's for:\n  - Mutations and automatic query syncing\n  - Query Refetching\n  - Atomic and Optimistic query manipulation\n\n</details>\n\n<details>\n<summary>Inspiration & Hat-Tipping</summary>\nA big thanks to both [Draqula](https://github.com/vadimdemedes/draqula) for inspiring a lot of React Query's original API and documentation and also [Zeit's SWR](https://github.com/zeit/swr) and it's creators for inspiring even further customizations and examples. You all rock!\n</details>\n\n## Examples\n\n- [CodeSandbox Playground](https://codesandbox.io/s/github/tannerlinsley/react-query/tree/master/examples/sandbox)\n- [Basic](./examples/basic)\n- [Custom Hooks](./examples/custom-hooks)\n- [Auto Refetching / Polling / Realtime](./examples/auto-refetching)\n- [Window Refocus Refetching](./examples/focus-refetching)\n- [Optimistic Updates](./examples/optimistic-updates)\n- [Load-More Pagination](./examples/load-more-pagination)\n\n# Documentation\n\n- [Installation](#installation)\n- [Queries](#queries)\n  - [Query Keys](#query-keys)\n  - [Query Variables](#query-variables)\n  - [Dependent Queries](#dependent-queries)\n  - [Caching & Invalidation](#caching--invalidation)\n  - [Pagination](#pagination)\n  - [Load-More/Infinite-Scroll Pagination](#load-more-pagination)\n  - [Scroll Restoration](#scroll-restoration)\n  - [Manual Querying](#manual-querying)\n  - [Retries](#retries)\n  - [Retry Delay](#retry-delay)\n- [Mutations](#mutations)\n  - [Basic Mutations](#basic-mutations)\n  - [Mutation Variables](#mutation-variables)\n  - [Invalidate and Refetch Queries from Mutations](#invalidate-and-refetch-queries-from-mutations)\n  - [Query Updates from Mutations](#query-updates-from-mutations)\n- [Manually or Optimistically Setting Query Data](#manually-or-optimistically-setting-query-data)\n- [Displaying Background Fetching Loading States](#displaying-background-fetching-loading-states)\n- [Displaying Global Background Fetching Loading State](#displaying-global-background-fetching-loading-state)\n- [Window-Focus Refetching](#window-focus-refetching)\n- [API](#api)\n  - [`useQuery`](#usequery)\n  - [`useMutation`](#usemutation)\n  - [`setQueryData`](#setquerydata)\n  - [`refetchQuery`](#refetchquery)\n  - [`refetchAllQueries`](#refetchallqueries)\n  - [`useIsFetching`](#useisfetching)\n  - [`useReactQueryConfig`](#usereactqueryconfig)\n\n## Installation\n\n```bash\n$ npm i --save react-query\n# or\n$ yarn add react-query\n```\n\n## Queries\n\nTo make a new query, call the `useQuery` hook with:\n\n- A **unique key for the query**\n- An **asynchronous function (or similar then-able)** to resolve the data\n\n```js\nconst info = useQuery('todos', fetchTodoList)\n```\n\nThe **unique key** you provide is used internally for refetching, caching, deduping related queries.\n\nThis key can be whatever you'd like it to be as long as:\n\n- It changes when your query should be requested again\n- It is consistent across all instances of that specific query in your application\n\nThe query `info` returned contains all information about the query and can be easily destructured and used in your component:\n\n```js\nfunction Todos() {\n  const { data, isLoading, error } = useQuery('todos', fetchTodoList)\n\n  return (\n    <div>\n      {isLoading ? (\n        <span>Loading...</span>\n      ) : error ? (\n        <span>Error: {error.message}</span>\n      ) : data ? (\n        <ul>\n          {data.map(todo => (\n            <li key={todo.id}>{todo.title}</li>\n          ))}\n        </ul>\n      ) : null}\n    </div>\n  )\n}\n```\n\n### Query Keys\n\nSince React Query uses a query's **unique key** for essentially everything, it's important to tailor them so that will change with your query requirements. In other libraries like Zeit's SWR, you'll see the use of URL's and GraphQL query template strings to achieve this, but we believe at scale, this becomes prone to typos and errors. To relieve this issue, you can pass a **tuple key** with a `string` and `object` of variables to deterministically get the the same key.\n\n> Pro Tip: Variables passed in the key are automatically passed to your query function!\n\nAll of the following queries would result in using the same key:\n\n```js\nuseQuery(['todos', { status, page }])\nuseQuery(['todos', { page, status }])\nuseQuery(['todos', { page, status, other: undefined }])\n```\n\n> Note: To aid you in your quest, if a query key is used that contains a `?` (like `todos?page=${page}&status=${status}`), you will see a gentle console warning to use the above format instead.\n\n### Query Variables\n\nTo use external props, state, or variables in a query function, pass them as a variables in your query key! They will be passed through to your query function as the first parameter.\n\n```js\nfunction Todos({ status }) {\n  const { data, isLoading, error } = useQuery(\n    ['todos', { status, page }],\n    fetchTodoList // This is the same as `fetchTodoList({ status, page })`\n  )\n}\n```\n\nWhenever a query's key changes, the query will automatically update:\n\n```js\nfunction Todos() {\n  const [page, setPage] = useState(0)\n\n  const { data, isLoading, error } = useQuery(\n    ['todos', { page }],\n    fetchTodoList\n  )\n\n  const onNextPage = () => {\n    setPage(page => page + 1)\n  }\n\n  return (\n    <>\n      {/* ... */}\n      <button onClick={onNextPage}>Load next page</button>\n    </>\n  )\n}\n```\n\n### Dependent Queries\n\nReact Query makes it easy to make queries that depends on other queries for both:\n\n- Parallel Queries (avoiding waterfalls) and\n- Serial Queries (when a piece of data is required for the next query to happen.\n\nTo do this effectively, you can use the following 2 approaches:\n\n#### Pass a falsey query key\n\nIf a query isn't ready to be requested yet, just pass a falsey value as the query key:\n\n```js\nconst { data: user } = useQuery(['user', { userId }])\nconst { data: projects } = useQuery(user && ['projects', { userId: user.id }]) // User is `null`, so the query key will be falsey\n```\n\n#### Use a query key function\n\nIf a function is passed, the query will not execute until the function can be called without throwing:\n\n```js\nconst { data: user } = useQuery(['user', { userId }])\nconst { data: projects } = useQuery(() => ['projects', { userId: user.id }]) // This will throw until `user` is available\n```\n\n#### Mix them together!\n\n```js\nconst [ready, setReady] = React.useState(false)\nconst { data: user } = useQuery(ready && ['user', { userId }]) // Wait for ready\nconst { data: projects } = useQuery(\n  () => ready && ['projects', { userId: user.id }] // Wait for ready and user.id\n```\n\n### Caching & Invalidation\n\nReact Query caching is automatic out of the box. It uses a `stale-while-revalidate` in-memory caching model across queries along with query deduping to to always ensure a query's data is only stored once even if that query is used multiple times across your application.\n\nAt a glance:\n\n- Caching is automatic and aggressive by default.\n- The cache is keyed on unique `query + variables` combinations.\n- By default query results become **stale** immediately after a successful fetch. This can be configured using the `staleTime` option at both the global and query-level)\n- Stale queries are automatically refetched whenever their **query keys change (this includes variables used in query key tuples)** or when **new usages/instances** of the query are mounted.\n- By default query results are **always** cached **when in use**.\n- If a query is no longer being used, it becomes inactive and by default is cached in the background for **5 minutes**. This time can be configured using the `cacheTime` option at both the global and query-level)\n- After a query is inactive for the time specified via the `cacheTime` option (defaults to 5 minutes), the query is deleted and garbage collected.\n\n<details>\n <summary>A more detailed example of the caching lifecycle</summary>\n\nLet's assume we are using the default `cacheTime` of **5 minutes** and the default `staleTime` of `0`.\n\n- A new instance of `useQuery('todos', fetchTodos)` mounts\n  - Since no other queries have been made with this query + variable combination, this query will show a hard loading state and make a network request to fetch the data.\n  - It will then cache the data using `'todos'` and `` as the unique identifiers for that cache.\n  - A stale invalidation is scheduled using the `staleTime` option as a delay (defaults to `0`, or immediately).\n- A second instance of `useQuery('todos', fetchTodos)` mounts elsewhere\n  - Because this exact data exist in the cache from the first instance of this query, that data is immediately returned from the cache\n  - Since the query is stale, it is refetched in the background automatically\n- Both instances of the `useQuery('todos', fetchTodos)` query are unmount and no longer in use.\n  - Since there are no more active instances to this query, a cache timeout is set using `cacheTime` to delete and garbage collect the query (defaults to **5 minutes**).\n- No more instances of `useQuery('todos', fetchTodos)` appear within **5 minutes**\n  - This query and its data is deleted and garbage collected.\n\n</details>\n\n> **Did You Know?** - Because React Query doesn't use document normalization in its cache (made popular with libraries like Apollo and Redux-Query), it eliminates a whole range of common issues with caching like incorrect data merges, failed cache reads/writes, and imperative maintenance of the cache.\n\n### Pagination\n\nIf all you need is page-based pagination, where the previous set of data is replaced with a new one, this section is not applicable to your use-case. For that, you can increment the page variable and pass it to your query via variables.\n\nHowever, if your app needs to add more data to the list along with existing one (for example, infinite loading), React Query provides you with a way to fetch additional data without deleting the current data. Let's use page-based pagination for simplicity, but assume that we want to append new todo items at the end of the list.\n\n```js\nfunction Todos() {\n  const { data, isLoading, error, refetch, isFetching } = useQuery(\n    ['todos', { page: 1 }],\n    fetchTodoList\n  )\n\n  const onFetchMore = () => {\n    refetch({\n      variables: { page: data.pagination.nextPage },\n      merge: (prev, next) => ({\n        ...next,\n        // Merge the new todos with the existing ones\n        todos: [...prev.todos, ...next.todos],\n      }),\n    })\n  }\n\n  return isLoading ? (\n    <span>Loading...</span>\n  ) : error ? (\n    <span>Error: {error.message}</span>\n  ) : data ? (\n    <>\n      <ul>\n        {data.todos.map(todo => (\n          <li key={todo.id}>{todo.title}</li>\n        ))}\n      </ul>\n      {data.pagination.hasMore && (\n        <button disabled={isFetching} onClick={onFetchMore}>\n          {isFetching ? 'Loading more todos...' : 'Load more todos'}\n        </button>\n      )}\n    </>\n  ) : null\n}\n```\n\n### Load-More/Infinite-Scroll Pagination\n\nRendering paginated lists that can \"load more\" data or \"infinite scroll\" is a common UI pattern. React Query supports some useful features for querying these types of lists. Let's assume we have an API that returns pages of `todos` 3 at a time based on a `cursor` index:\n\n```js\nfetch('/api/projects?cursor=0'\n// { data: [...], nextId: 3}\nfetch('/api/projects?cursor=3'\n// { data: [...], nextId: 6}\nfetch('/api/projects?cursor=6'\n// { data: [...], nextId: 9}\n```\n\nUsing the `nextId` value in each page's response, we can configure `useQuery` to fetch more pages as needed:\n\n- Configure your query function to use optional pagination variables. We'll send through the `nextId` as the `cursor` for the next page request\n- Set the `paginated` option to `true`\n- Define a `getCanFetchMore` option to know if there is more data to load (it receives the `lastPage` and `allPages` as parameters)\n\n```js\nimport { useQuery } from 'react-query'\n\nfunction Todos() {\n  const {\n    data: pages,\n    isLoading,\n    isFetching,\n    isFetchingMore,\n    fetchMore,\n    canFetchMore,\n  } = useQuery(\n    'todos',\n    ({ nextId } = {}) => fetch('/api/projects?cursor=' + (nextId || 0)),\n    {\n      paginated: true,\n      getCanFetchMore: (lastPage, allPages) => next.nextId,\n    }\n  )\n\n  // ...\n}\n```\n\nYou'll notice a few new things now:\n\n- `data` is now an array of pages that contain query results, instead of the query results themselves\n- A `fetchMore` function is now available\n- A `canFetchMore` boolean is now available\n- An `isFetchingMore` boolean is now available\n\nThese can now be used to render a \"load more\" list (this example uses an `offset` key):\n\n```js\nimport { useQuery } from 'react-query'\n\nfunction Todos() {\n  const {\n    data: pages,\n    isLoading,\n    isFetching,\n    isFetchingMore,\n    fetchMore,\n    canFetchMore,\n  } = useQuery(\n    'projects',\n    ({ offset } = {}) => fetch('/api/projects?offset=' + (offset || 0)),\n    {\n      paginated: true,\n      getCanFetchMore: (lastPage, allPages) => next.nextId,\n    }\n  )\n\n  const loadMore = async () => {\n    try {\n      // Get the last page\n      const lastPage = data[data.length - 1]\n      // Get the last item's ID\n      const lastItemId = lastPage[lastPage.length - 1].id\n      // Fetch more with the offset ID + 1\n      await fetchMore({\n        offset: lastItemId + 1,\n      })\n    } catch {}\n  }\n\n  return isLoading ? (\n    <p>Loading...</p>\n  ) : data ? (\n    <>\n      {data.map((page, i) => (\n        <React.Fragment key={i}>\n          {page.data.map(project => (\n            <p key={project.id}>{project.name}</p>\n          ))}\n        </React.Fragment>\n      ))}\n      <div>\n        {canFetchMore ? (\n          <button onClick={loadMore} disabled={isFetchingMore}>\n            {isFetchingMore ? 'Loading more...' : 'Load More'}\n          </button>\n        ) : (\n          'Nothing more to fetch.'\n        )}\n      </div>\n      <div>\n        {isFetching && !isFetchingMore ? 'Background Updating...' : null}\n      </div>\n    </>\n  ) : null\n}\n```\n\n#### What happens when a paginated query needs to be refetched?\\*\\*\n\nWhen a paginated query becomes `stale` and needs to be refetched, each page is fetched `individually` with the same variables that were used to request it originally. If a paginated query's results are ever removed from the cache, the pagination restarts at the initial state with a single page being requested.\n\n### Scroll Restoration\n\nOut of the box, \"scroll restoration\" Just Works™️ in React Query. The reason for this is that query results are cached and retrieved synchronously when rendered. As long as a query is cached and has not been garbage collected, you should never experience problems with scroll restoration.\n\n### Manual Querying\n\nIf you ever want to disable a query from automatically running, you can use the `manual = true` option. When `manual` is set to true:\n\n- The query will not automatically refetch due to changes to their query function or variables.\n- The query will not automatically refetch due to `refetchQueries` options in other queries or via `useRefetchQuery` calls.\n\n```js\nfunction Todos() {\n  const { data, isLoading, error, refetch, isFetching } = useQuery(\n    'todos',\n    fetchTodoList,\n    {\n      manual: true,\n    }\n  )\n\n  return (\n    <>\n      <button onClick={() => refetch()}>Fetch Todos</button>\n\n      {isLoading ? (\n        <span>Loading...</span>\n      ) : error ? (\n        <span>Error: {error.message}</span>\n      ) : data ? (\n        <>\n          <ul>\n            {data.map(todo => (\n              <li key={todo.id}>{todo.title}</li>\n            ))}\n          </ul>\n        </>\n      ) : null}\n    </>\n  )\n}\n```\n\n> Pro Tip: Don't use `manual` for dependent queries. Use [Dependent Queries](#dependent-queries) instead!\n\n### Retries\n\nWhen a `useQuery` query fails (the function throws an error), React Query will automatically retry the query if that query's request has not reached the max number of consecutive retries (defaults to `3`).\n\nYou can configure retries both on a global level and an individual query level.\n\n- Setting `retry = false` will disable retries\n- Setting `retry = 6` will retry failing requests 6 times before showing the final error thrown by the function\n- Setting `retry = true` will infinitely retry failing requests.\n\n```js\nimport { useReactQueryConfig } from 'react-query'\n\n// Turn off retries for all queries\nuseReactQueryConfig({\n  retry: false,\n})\n\n// Make specific query retry a certain number of times\nconst { data, isLoading, error } = useQuery(\n  ['todos', { page: 1 }],\n  fetchTodoList,\n  {\n    retry: 10, // Will retry failed requests 10 times before displaying an error\n  }\n)\n```\n\n### Retry Delay\n\nBy default, retries in React Query do not happen immediately after a request fails. As is standard, a back-off delay is gradually applied to each retry attempt.\n\nThe default `retryDelay` is set to double (starting at `1000`ms) with each attempt, but not exceed 30 seconds:\n\n```js\n// Configure for all queries\nimport { useReactQueryConfig } from 'react-query'\n\nconst config = {\n  retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),\n}\n\nfunction App() {\n  useReactQueryConfig(config)\n\n  return <Stuff />\n}\n```\n\nThough it is not recommended, you can obviously override the `retryDelay` function/integer in both the Provider and individual query options. If set to an integer instead of a function the delay will always be the same amount of time:\n\n```js\nconst { data, isLoading, error } = useQuery('todos', fetchTodoList, {\n  retryDelay: 10000, // Will always wait 1000ms to retry, regardless of how many retries\n})\n```\n\n## Mutations\n\nUnlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, React Query exports a `useMutation` hook.\n\n### Basic Mutations\n\nAssuming the server implements a ping mutation, that returns \"pong\" string, here's an example of the most basic mutation:\n\n```js\nconst PingPong = () => {\n  const [mutate, { data, isLoading, error }] = useMutation(pingMutation)\n\n  const onPing = async () => {\n    try {\n      const data = await mutate()\n      console.log(data)\n      // { ping: 'pong' }\n    } catch {\n      // Uh oh, something went wrong\n    }\n  }\n  return <button onClick={onPing}>Ping</button>\n}\n```\n\nMutations without variables are not that useful, so let's add some variables to closer match reality.\n\n### Mutation Variables\n\nTo pass `variables` to your `mutate` function, call `mutate` with an object.\n\n```js\nconst CreateTodo = () => {\n  const [title, setTitle] = useState('')\n  const [mutate] = useMutation(createTodo)\n\n  const onCreateTodo = async e => {\n    // Prevent the form from refreshing the page\n    e.preventDefault()\n\n    try {\n      await mutate({ title })\n      // Todo was successfully created\n    } catch (error) {\n      // Uh oh, something went wrong\n    }\n  }\n\n  return (\n    <form onSubmit={onCreateTodo}>\n      <input\n        type=\"text\"\n        value={title}\n        onChange={e => setTitle(e.target.value)}\n      />\n      <br />\n      <button type=\"submit\">Create Todo</button>\n    </form>\n  )\n}\n```\n\nEven with just variables, mutations aren't all that special, but when used with the `refetchQueries` and `updateQuery` options, they become a very powerful tool.\n\n### Invalidate and Refetch Queries from Mutations\n\nWhen a mutation succeeds, it's likely that other queries in your application need to update. Where other libraries that use normalized caches would attempt to update locale queries with the new data imperatively, React Query avoids the pitfalls that come with normalized caches and prescribes **atomic updates** instead of partial cache manipulation.\n\nFor example, assume we have a mutation to post a new todo:\n\n```js\nconst [mutate] = useMutation(postTodo)\n```\n\nWhen a successful `postTodo` mutation happens, we likely want all `todos` queries to get refetched to show the new todo item. To do this, you can use the `refetchQueries` option when calling a mutation's `mutate` function.\n\n```js\n// When this mutation succeeds, any queries with the `todos` or `reminders` query key will be refetched\nmutate(newTodo, { refetchQueries: ['todos', 'reminders'], })\n\n// The 3 queries below will be refetched when the mutation above succeeds\nconst todoListQuery = useQuery('todos', fetchTodoList)\nconst todoListQuery = useQuery(['todos', { page: 1 }, fetchTodoList)\nconst remindersQuery = useQuery('reminders', fetchReminders)\n```\n\nYou can even refetch queries with specific variables by passing a query key tuple to `refetchQueries`:\n\n```js\nmutate(newTodo, { refetchQueries: [['todos', { status: 'done' }]] })\n\n// The query below will be refetched when the mutation above succeeds\nconst todoListQuery = useQuery(['todos', { status: 'done' }], fetchTodoList)\n// However, the following query below will NOT be refetched\nconst todoListQuery = useQuery('todos', fetchTodoList)\n```\n\nIf you want to **only** refetch `todos` queries that don't have variables, you can pass a tuple with `variables` set to `false`:\n\n```js\nmutate(newTodo, { refetchQueries: [['todos', false]] })\n\n// The query below will be refetched when the mutation above succeeds\nconst todoListQuery = useQuery(['todos'], fetchTodoList)\n// However, the following query below will NOT be refetched\nconst todoListQuery = useQuery(['todos', { status: 'done' }], fetchTodoList)\n```\n\nIf you prefer that the promise returned from `mutate()` only resolves **after** any `refetchQueries` have been refetched, you can pass the `waitForRefetchQueries = true` option to `mutate`:\n\n```js\nconst [mutate] = useMutation(addTodo, { refetchQueries: ['todos'] })\n\nconst run = async () => {\n  try {\n    await mutate(todo, { waitForRefetchQueries: true })\n    console.log('I will only log after all refetchQueries are done refetching!')\n  } catch {}\n}\n```\n\nIt's important to note that `refetchQueries` by default will only happen after a successful mutation (the mutation function doesn't throw an error). If you would like to refetch the `refetchQueries` regardless of this, you can set `refetchQueriesOnFailure` to `true` in your `mutate` options:\n\n```js\nconst [mutate] = useMutation(addTodo, { refetchQueries: ['todos'] })\n\nconst run = async () => {\n  try {\n    await mutate(todo, { refetchQueriesOnFailure: true })\n    // Even if the above mutation fails, any `todos` queries will still be refetched.\n  } catch {}\n}\n```\n\n### Query Updates from Mutations\n\nWhen dealing with mutations that **update** objects on the server, it's common for the new object to be automatically returned in the response of the mutation. Instead of invalidating any queries for that item and wasting a network call to refetch them again, we can take advantage of the object returned by the mutation function and update any query responses with that data that match that query using the `updateQuery` option:\n\n```js\nconst [mutate] = useMutation(editTodo)\n\nmutate(\n  {\n    id: 5,\n    name: 'Do the laundry',\n  },\n  {\n    updateQuery: ['todo', { id: 5 }],\n  }\n)\n\n// The query below will be updated with the response from the mutation above when it succeeds\nconst { data, isLoading, error } = useQuery(['todo', { id: 5 }], fetchTodoByID)\n```\n\n## Manually or Optimistically Setting Query Data\n\nIn rare circumstances, you may want to manually update a query's response before it has been refetched. To do this, you can use the exported `setQueryData` function:\n\n```js\nimport { setQueryData } from 'react-query'\n\n// Full replacement\nsetQueryData(['todo', { id: 5 }], newTodo)\n\n// or functional update\nsetQueryData(['todo', { id: 5 }], previous => ({ ...previous, status: 'done' }))\n```\n\n**Most importantly**, when manually setting a query response, it naturally becomes out-of-sync with it's original source. To ease this issue, `setQueryData` automatically triggers a background refresh of the query after it's called to ensure it eventually synchronizes with the original source.\n\nShould you choose that you do _not_ want to refetch the query automatically, you can set the `shouldRefetch` option to `false`:\n\n```js\nimport { setQueryData } from 'react-query'\n\n// Mutate, but do not automatically refetch the query in the background\nsetQueryData(['todo', { id: 5 }], newTodo, {\n  shouldRefetch: false,\n})\n```\n\n## Displaying Background Fetching Loading States\n\nA query's `isLoading` boolean is usually sufficient to show the initial hard-loading state for a query, but sometimes you may want to display a more subtle indicator that a query is refetching in the background. To do this, queries also supply you with an `isFetching` boolean that you can use to show that it's in a fetching state:\n\n```js\nfunction Todos() {\n  const { data: todos, isLoading, isFetching } = useQuery('todos', fetchTodos)\n\n  return isLoading ? (\n    <span>Loading...</span>\n  ) : todos ? (\n    <>\n      {isFetching ? <div>Refreshing...</div> : null}\n\n      <div>\n        {todos.map(todo => (\n          <Todo todo={todo} />\n        ))}\n      </div>\n    </>\n  ) : null\n}\n```\n\n## Displaying Global Background Fetching Loading State\n\nIn addition to individual query loading states, if you would like to show a global loading indicator when **any** queries are fetching (including in the background), you can use the `useIsFetching` hook:\n\n```js\nimport { useIsFetching } from 'react-query'\n\nfunction GlobalLoadingIndicator() {\n  const isFetching = useIsFetching()\n\n  return isFetching ? (\n    <div>Queries are fetching in the background...</div>\n  ) : null\n}\n```\n\n## Window-Focus Refetching\n\nIf a user leaves your application and returns to stale data, you may want to trigger an update in the background to update any stale queries. Thankfully, **React Query does this automatically for you**, but if you choose to disable it, you can use the `useReactQueryConfig`'s `refetchAllOnWindowFocus` option to disable it:\n\n```js\nuseReactQueryConfig({ refetchAllOnWindowFocus: false })\n```\n\n# API\n\n## `useQuery`\n\n```js\nconst {\n  data,\n  error,\n  isFetching,\n  isCached,\n  failureCount,\n  isLoading,\n  refetch,\n  // with pagination mode enabled\n  isFetchingMore,\n  canFetchMore,\n  fetchMore,\n} = useQuery(queryKey, queryFn, {\n  manual,\n  pagination,\n  getCanFetchMore,\n  staleTime,\n  retry,\n  retryDelay,\n})\n```\n\n### Options\n\n- `queryKey: String | [String, Variables: Object] | falsey | Function => queryKey`\n  - **Required**\n  - The query key to use for this query.\n  - If a string is passed, it will be used as the query key\n  - If a `[String, Object]` tuple is passed, they will be serialized into a stable query key. See [Query Keys](#query-keys) for more information.\n  - If a falsey value is passed, the query will be disabled and not run automatically.\n  - If a function is passed, it should resolve to any other valid query key type. If the function throws, the query will be disabled and not run automatically.\n  - The query will automatically update when this key changes (if the key is not falsey and if `manual` is not set to `true`)\n  - `Variables: Object`\n    - If a tuple with variables is passed, this object should be **serializable**.\n    - Nested arrays and objects are supported\n    - The order of object keys is sorted to be stable before being serialized into the query key\n- `queryFn: Function(variables) => Promise(data/error)`\n  - **Required**\n  - The function that the query will use to request data\n  - Optionally receives the `variables` object passed from either the query key tuple (`useQuery(['todos', variables], queryFn)`) or the refetch method's `variables` option `refetch({ variables })`\n  - Must return a promise that will either resolves data or throws an error.\n- `pagination: Boolean`\n  - Set this to `true` to enable pagination mode\n  - In this mode, new pagination utilities are returned from `useQuery` and `data` becomes an array of page results\n- `manual: Boolean`\n  - Set this to `true` to disable automatic refetching when the query mounts or changes query keys.\n  - To refetch the query, use the `refetch` method returned from the `useQuery` instance.\n- `getCanFetchMore: Function(lastPage, allPages) => Boolean`\n  - **Required if using `pagination` mode**\n  - When using `pagination` mode, this function should return `true` if there is more data than can be fetched.\n- `staleTime`\n  - [See `useReactQueryConfig` options...](#usereactqueryconfig)\n- `retry`\n  - [See `useReactQueryConfig` options...](#usereactqueryconfig)\n- `retryDelay`\n  - [See `useReactQueryConfig` options...](#usereactqueryconfig)\n\n### Returns\n\n- `data: null | Any`\n  - Defaults to `null`\n  - The last successfully resolved data for the query.\n- `error: null | Error`\n  - The error object for the query, if an error was thrown.\n- `isLoading: Boolean`\n  - Will be `true` if the query is both fetching and does not have any cached data to display.\n- `isFetching: Boolean`\n  - Will be `true` if the query is currently fetching, including background fetching.\n- `isCached: Boolean`\n  - Will be `true` if the query's response is currently cached.\n- `failureCount: Integer`\n  - The failure count for the query.\n  - Incremented every time the query fails.\n  - Reset to `0` when the query succeeds.\n- `refetch: Function({ variables: Object, merge: Function, disableThrow: Boolean })`\n  - A function to manually refetch the query.\n  - Supports custom variables (useful for \"fetch more\" calls)\n  - Supports custom data merging (useful for \"fetch more\" calls)\n  - Set `disableThrow` to true to disable this function from throwing if an error is encountered.\n- `isFetchingMore: Boolean`\n  - If using `pagination` mode, this will be `true` when fetching more results using the `fetchMore` function.\n- `canFetchMore: Boolean`\n  - If using `pagination` mode, this will be `true` if there is more data to be fetched (known via the required `getCanFetchMore` option function)\n- `fetchMore: Function(variables) => Promise`\n  - If using `pagination` mode, this function allows you to fetch the next \"page\" of results.\n  - `variables` should be an object that is passed to your query function to retrieve the next page of results\n\n## `useMutation`\n\n```js\nconst [mutate, { data, isLoading, error }] = useMutation(mutationFn, {\n  refetchQueries,\n  refetchQueriesOnFailure,\n})\n\nconst promise = mutate(variables, { updateQuery, waitForRefetchQueries })\n```\n\n### Options\n\n- `mutationFn: Function(variables) => Promise`\n  - **Required**\n  - A function that performs an asynchronous task and returns a promise\n- `refetchQueries: Array<QueryKey>`\n  - Optional\n  - When the mutation succeeds, these queries will be automatically refetched\n  - Must be an array of query keys, eg. `['todos', ['todo', { id: 5 }], 'reminders']`\n- `refetchQueriesOnFailure: Boolean`\n  - Defaults to `false`\n  - Set this to `true` if you want `refetchQueries` to be refetched regardless of the mutation succeeding.\n- `variables: any`\n  - Optional\n  - The variables object to pass tot he `mutationFn`\n- `updateQuery: QueryKey`\n  - Optional\n  - The query key for the individual query to update with the response from this mutation.\n  - Suggested use is for `update` mutations that regularly return the updated data with the mutation. This saves you from making another unnecessary network call to refetch the data.\n- `waitForRefetchQueries: Boolean`\n  - Optional\n  - If set to `true`, the promise returned by `mutate()` will not resolve until refetched queries are resolved as well.\n\n### Returns\n\n- `mutate: Function(variables, { updateQuery })`\n  - The mutation function you can call with variables to trigger the mutation and optionally update a query with its response.\n- `data: null | Any`\n  - Defaults to `null`\n  - The last successfully resolved data for the query.\n- `error: null | Error`\n  - The error object for the query, if an error was thrown.\n- `isLoading: Boolean`\n  - Will be `true` if the query is both fetching and does not have any cached data\n- `promise: Promise`\n  - The promise that is returned by the `mutationFn`\n\n## `setQueryData`\n\n`setQueryData` is a function for imperatively updating the response of a query. By default, this function also triggers a background refetch to ensure that the data is eventually consistent with the remote source, but this can be disabled.\n\n```js\nimport { setQueryData } from 'react-query'\n\nconst maybePromise = setQueryData(queryKey, data, { shouldRefetch })\n```\n\n### Options\n\n- `queryKey: QueryKey`\n  - **Required**\n  - The query key for the individual query to update with new data.\n- `data: any | Function(old) => any`\n  - **Required**\n  - Must either be the new data or a function that receives the old data and returns the new data\n- `shouldRefetch: Boolean`\n  - Optional\n  - Defaults to `true`\n  - Set this to `false` to disable the automatic background refetch from happening\n\n### Returns\n\n- `maybePromise: undefined | Promise`\n  - If `shouldRefetch` is `true`, a promise is returned that will either resolve when the query refetch is complete or will reject if the refetch fails (after its respective retry configurations is done).\n\n## `refetchQuery`\n\n`refetchQuery` is a function for imperatively triggering a refetch of either:\n\n- A group of queries\n- A single query\n\nBy default, it will only refetch stale queries, but the `force` option can be used to refetch all queries, including non-stale ones.\n\n```js\nimport { refetchQuery } from 'react-query'\n\nconst promise = refetchQuery(queryKey, { force })\n```\n\n### Options\n\n- `queryKey: QueryKey`\n  - **Required**\n  - The query key for the query or query group to refetch.\n  - If a single `string` is passed, any queries using that `string` or any tuple key queries that include that `string` (eg. passing `todos` would refetch both `todos` and `['todos', { status: 'done' }]`).\n  - If a tuple key is passed, only the exact query with that key will be refetched (eg. `['todos', { status: 'done' }]` will only refetch queries with that exact key)\n  - If a tuple key is passed with the `variables` slot set to `false`, then only queries that match the `string` key and have no variables will be refetched (eg. `['todos', false]` would only refetch `todos` and not `['todos', { status: 'done' }]`)\n- `force: Boolean`\n  - Optional\n  - Set this to true to force all queries to refetch instead of only stale ones.\n\n### Returns\n\n- `promise: Promise`\n  - A promise is returned that will either resolve when all refetch queries are complete or will reject if any refetch queries fail (after their respective retry configurations are done).\n\n## `refetchAllQueries`\n\n`refetchAllQueries` is a function for imperatively triggering a refetch of all queries. By default, it will only refetch stale queries, but the `force` option can be used to refetch all queries, including non-stale ones.\n\n```js\nimport { refetchAllQueries } from 'react-query'\n\nconst promise = refetchAllQueries({ force, includeInactive })\n```\n\n### Options\n\n- `force: Boolean`\n  - Optional\n  - Set this to `true` to force all queries to refetch instead of only stale ones.\n- `includeInactive: Boolean`\n  - Optional\n  - Set this to `true` to also refetch inactive queries.\n  - Overrides the `force` option to be `true`, regardless of it's value.\n\n### Returns\n\n- `promise: Promise`\n  - A promise is returned that will either resolve when all refetch queries are complete or will reject if any refetch queries fail (after their respective retry configurations are done).\n\n## `useIsFetching`\n\n`useIsFetching` is an optional hook that returns true if any query in your application is loading for fetching in the background (useful for app-wide loading indicators)\n\n```js\nimport { useIsFetching } from 'react-query'\n\nconst isFetching = useIsFetching()\n```\n\n### Returns\n\n- `isFetching: Boolean`\n  - Will be `true` if any query in your application is loading or fetching in the background\n\n## `useReactQueryConfig`\n\n`useReactQueryConfig` is optional and can be used to define defaults for all instances of `useQuery` through your app:\n\n```js\nimport { useReactQueryConfig } from 'react-query'\n\nuseReactQueryConfig({\n  retry,\n  retryDelay,\n  staleTime,\n  invalidCacheTime,\n})\n```\n\n### Options\n\nPass options to `useReactQueryConfig` by pass it a `config` prop:\n\n- `retry: Boolean | Int`\n  - If `false`, failed queries will not retry by default\n  - If `true`, failed queries will retry infinitely\n  - If set to an `Int`, eg. `3`, failed queries will retry until the failed query count meets that number\n- `retryDelay: Function(retryAttempt: Int) => Int`\n  - This function receives a `retryAttempt` integer and returns the delay to apply before the next attempt in milliseconds\n  - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff\n  - A function like `attempt => attempt * 1000` applies linear backoff.\n- `staleTime: Int`\n  - The time in milliseconds that cache data remains fresh. After a successful cache update, that cache data will become stale after this duration\n- `invalidCacheTime: Int`\n  - The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration.\n\n### Returns\n\nThis hook does not return anything\n\n### Example\n\n```js\nconst config = {\n  // These are the default config options for the useReactQueryConfig\n  retry: 3,\n  retryDelay: attempt =>\n    Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000),\n  staleTime: 10 * 1000, // 10 seconds\n  invalidCacheTime: 10 * 1000, // 10 seconds\n}\n\nfunction App() {\n  useReactQueryConfig({\n    retry: 4\n  })\n\n  return </>\n}\n```\n","license":"MIT","scripts":{"test":"cross-env CI=1 react-scripts test --env=jsdom","build":"rollup -c","start":"rollup -c -w","format":"prettier {src,src/**,example/src,example/src/**}/*.{md,js,jsx,tsx} --write","prepare":"yarn build","release":"yarn publish","now-build":"yarn && cd www && yarn && yarn build","test:watch":"react-scripts test --env=jsdom","releaseNext":"yarn publish --tag next"},"_npmUser":{"name":"tannerlinsley","email":"tannerlinsley@gmail.com"},"repository":{"url":"https://github.com/tannerlinsley/react-query.git","type":"git"},"description":"Hooks for managing, caching and syncing asynchronous and remote data in React","directories":{},"maintainers":[{"name":"tannerlinsley","email":"tannerlinsley@gmail.com"}],"dependencies":{"core-js":"3","fast-async":"^6.3.8","@babel/plugin-transform-regenerator":"^7.4.5"},"_hasShrinkwrap":false,"readmeFilename":"README.md","devDependencies":{"react":"^16.8.6","eslint":"5.x","rollup":"^1.12.4","prettier":"^1.18.2","cross-env":"^5.1.4","react-dom":"^16.8.6","babel-core":"7.0.0-bridge.0","@svgr/rollup":"^4.3.0","babel-eslint":"9.x","@babel/preset-env":"^7.4.5","eslint-plugin-node":"^9.1.0","@babel/preset-react":"^7.0.0","eslint-plugin-react":"7.x","rollup-plugin-babel":"^4.3.2","eslint-plugin-import":"2.x","eslint-plugin-promise":"^4.1.1","eslint-config-prettier":"^4.3.0","eslint-config-standard":"^12.0.0","eslint-plugin-flowtype":"2.x","eslint-plugin-jsx-a11y":"6.x","eslint-plugin-prettier":"^3.1.0","eslint-plugin-standard":"^4.0.0","rollup-plugin-commonjs":"^10.0.0","eslint-config-react-app":"^4.0.1","eslint-plugin-react-hooks":"1.5.0","rollup-plugin-node-resolve":"^5.0.0","eslint-config-standard-react":"^7.0.2","rollup-plugin-peer-deps-external":"^2.2.0","@babel/plugin-proposal-class-properties":"^7.4.4"},"peerDependencies":{"react":"^16.6.3"},"_npmOperationalInternal":{"tmp":"tmp/react-query_0.1.1-alpha.0_1572910996958_0.19045383583107678","host":"s3://npm-registry-packages"},"_id":"react-query@0.1.1-alpha.0","version":"0.1.1-alpha.0"}