SIGN IN SIGN UP
TanStack / query UNCLAIMED

🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.

48947 0 0 TypeScript
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
---
id: QueryClient
title: QueryClient
---
## `QueryClient`
The `QueryClient` can be used to interact with a cache:
```tsx
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
import { QueryClient } from '@tanstack/react-query'
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: Infinity,
},
},
})
await queryClient.prefetchQuery({ queryKey: ['posts'], queryFn: fetchPosts })
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
```
Its available methods are:
- [`queryClient.fetchQuery`](#queryclientfetchquery)
- [`queryClient.fetchInfiniteQuery`](#queryclientfetchinfinitequery)
- [`queryClient.prefetchQuery`](#queryclientprefetchquery)
- [`queryClient.prefetchInfiniteQuery`](#queryclientprefetchinfinitequery)
- [`queryClient.getQueryData`](#queryclientgetquerydata)
- [`queryClient.ensureQueryData`](#queryclientensurequerydata)
- [`queryClient.ensureInfiniteQueryData`](#queryclientensureinfinitequerydata)
- [`queryClient.getQueriesData`](#queryclientgetqueriesdata)
- [`queryClient.setQueryData`](#queryclientsetquerydata)
- [`queryClient.getQueryState`](#queryclientgetquerystate)
- [`queryClient.setQueriesData`](#queryclientsetqueriesdata)
- [`queryClient.invalidateQueries`](#queryclientinvalidatequeries)
- [`queryClient.refetchQueries`](#queryclientrefetchqueries)
- [`queryClient.cancelQueries`](#queryclientcancelqueries)
- [`queryClient.removeQueries`](#queryclientremovequeries)
- [`queryClient.resetQueries`](#queryclientresetqueries)
- [`queryClient.isFetching`](#queryclientisfetching)
- [`queryClient.isMutating`](#queryclientismutating)
- [`queryClient.getDefaultOptions`](#queryclientgetdefaultoptions)
- [`queryClient.setDefaultOptions`](#queryclientsetdefaultoptions)
- [`queryClient.getQueryDefaults`](#queryclientgetquerydefaults)
- [`queryClient.setQueryDefaults`](#queryclientsetquerydefaults)
- [`queryClient.getMutationDefaults`](#queryclientgetmutationdefaults)
- [`queryClient.setMutationDefaults`](#queryclientsetmutationdefaults)
- [`queryClient.getQueryCache`](#queryclientgetquerycache)
- [`queryClient.getMutationCache`](#queryclientgetmutationcache)
- [`queryClient.clear`](#queryclientclear)
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
- [`queryClient.resumePausedMutations`](#queryclientresumepausedmutations)
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
**Options**
- `queryCache?: QueryCache`
- Optional
- The query cache this client is connected to.
- `mutationCache?: MutationCache`
- Optional
- The mutation cache this client is connected to.
- `defaultOptions?: DefaultOptions`
- Optional
- Define defaults for all queries and mutations using this queryClient.
- You can also define defaults to be used for [hydration](../framework/react/reference/hydration.md)
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
## `queryClient.fetchQuery`
`fetchQuery` is an asynchronous method that can be used to fetch and cache a query. It will either resolve with the data or throw with the error. Use the `prefetchQuery` method if you just want to fetch a query without needing the result.
If the query exists and the data is not invalidated or older than the given `staleTime`, then the data from the cache will be returned. Otherwise it will try to fetch the latest data.
```tsx
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
try {
const data = await queryClient.fetchQuery({ queryKey, queryFn })
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
} catch (error) {
console.log(error)
}
```
Specify a `staleTime` to only fetch when the data is older than a certain amount of time:
```tsx
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
try {
const data = await queryClient.fetchQuery({
queryKey,
queryFn,
staleTime: 10000,
})
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
} catch (error) {
console.log(error)
}
```
**Options**
The options for `fetchQuery` are exactly the same as those of [`useQuery`](../framework/react/reference/useQuery.md), except the following: `enabled, refetchInterval, refetchIntervalInBackground, refetchOnWindowFocus, refetchOnReconnect, refetchOnMount, notifyOnChangeProps, throwOnError, select, suspense, placeholderData`; which are strictly for useQuery and useInfiniteQuery. You can check the [source code](https://github.com/TanStack/query/blob/7cd2d192e6da3df0b08e334ea1cf04cd70478827/packages/query-core/src/types.ts#L119) for more clarity.
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
**Returns**
- `Promise<TData>`
## `queryClient.fetchInfiniteQuery`
`fetchInfiniteQuery` is similar to `fetchQuery` but can be used to fetch and cache an infinite query.
```tsx
try {
const data = await queryClient.fetchInfiniteQuery({ queryKey, queryFn })
console.log(data.pages)
} catch (error) {
console.log(error)
}
```
**Options**
The options for `fetchInfiniteQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
**Returns**
- `Promise<InfiniteData<TData, TPageParam>>`
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
## `queryClient.prefetchQuery`
2021-02-11 13:51:12 +01:00
`prefetchQuery` is an asynchronous method that can be used to prefetch a query before it is needed or rendered with `useQuery` and friends. The method works the same as `fetchQuery` except that it will not throw or return any data.
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
```tsx
await queryClient.prefetchQuery({ queryKey, queryFn })
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
```
You can even use it with a default queryFn in your config!
```tsx
await queryClient.prefetchQuery({ queryKey })
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
```
**Options**
The options for `prefetchQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
**Returns**
- `Promise<void>`
- A promise is returned that will either immediately resolve if no fetch is needed or after the query has been executed. It will not return any data or throw any errors.
## `queryClient.prefetchInfiniteQuery`
`prefetchInfiniteQuery` is similar to `prefetchQuery` but can be used to prefetch and cache an infinite query.
```tsx
await queryClient.prefetchInfiniteQuery({ queryKey, queryFn })
```
**Options**
The options for `prefetchInfiniteQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
**Returns**
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
- `Promise<void>`
- A promise is returned that will either immediately resolve if no fetch is needed or after the query has been executed. It will not return any data or throw any errors.
## `queryClient.getQueryData`
`getQueryData` is a synchronous function that can be used to get an existing query's cached data. If the query does not exist, `undefined` will be returned.
```tsx
const data = queryClient.getQueryData(queryKey)
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
```
**Options**
- `queryKey: QueryKey`: [Query Keys](../framework/react/guides/query-keys.md)
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
**Returns**
- `data: TQueryFnData | undefined`
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
- The data for the cached query, or `undefined` if the query does not exist.
## `queryClient.ensureQueryData`
`ensureQueryData` is an asynchronous function that can be used to get an existing query's cached data. If the query does not exist, `queryClient.fetchQuery` will be called and its results returned.
```tsx
const data = await queryClient.ensureQueryData({ queryKey, queryFn })
```
**Options**
- the same options as [`fetchQuery`](#queryclientfetchquery)
- `revalidateIfStale: boolean`
- Optional
- Defaults to `false`
- If set to `true`, stale data will be refetched in the background, but cached data will be returned immediately.
**Returns**
- `Promise<TData>`
## `queryClient.ensureInfiniteQueryData`
`ensureInfiniteQueryData` is an asynchronous function that can be used to get an existing infinite query's cached data. If the query does not exist, `queryClient.fetchInfiniteQuery` will be called and its results returned.
```tsx
const data = await queryClient.ensureInfiniteQueryData({
queryKey,
queryFn,
initialPageParam,
getNextPageParam,
})
```
**Options**
- the same options as [`fetchInfiniteQuery`](#queryclientfetchinfinitequery)
- `revalidateIfStale: boolean`
- Optional
- Defaults to `false`
- If set to `true`, stale data will be refetched in the background, but cached data will be returned immediately.
**Returns**
- `Promise<InfiniteData<TData, TPageParam>>`
## `queryClient.getQueriesData`
`getQueriesData` is a synchronous function that can be used to get the cached data of multiple queries. Only queries that match the passed queryKey or queryFilter will be returned. If there are no matching queries, an empty array will be returned.
```tsx
const data = queryClient.getQueriesData(filters)
```
**Options**
- `filters: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
- if a filter is passed, the data with queryKeys matching the filter will be returned
**Returns**
- `[queryKey: QueryKey, data: TQueryFnData | undefined][]`
- An array of tuples for the matched query keys, or `[]` if there are no matches. The tuples are the query key and its associated data.
**Caveats**
Because the returned data in each tuple can be of varying structures (i.e. using a filter to return "active" queries can return different data types), the `TData` generic defaults to `unknown`. If you provide a more specific type to `TData` it is assumed that you are certain each tuple's data entry is all the same type.
This distinction is more a "convenience" for ts devs that know which structure will be returned.
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
## `queryClient.setQueryData`
feat: beta release (#5771) * release: v5.0.0-alpha.11 * refactor(core): unify hydration options (#5131) * refactor: unify hydration options * docs: update hydration docs * migration guide * refactor: use shouldDehydrate... syntax * Update docs/react/guides/migrating-to-v5.md Co-authored-by: Fredrik Höglund <fredrik.hoglund@gmail.com> * Apply suggestions from code review * chore: fix tests * chore: fix tests * Update docs/react/reference/hydration.md --------- Co-authored-by: Fredrik Höglund <fredrik.hoglund@gmail.com> * release: v5.0.0-alpha.12 * release: v5.0.0-alpha.13 * chore: remove unused devDependencies (#5211) * refactor(react-query-devtools): move devtools components in files (#5150) * refactor(react-query-devtools): move QueryStatusCount header to subdirectory * refactor(react-query-devtools): move QueryRow to subdirectory * refactor(react-query-devtools): move ActiveQuery to subdirectory * refactor(react-query-devtools): move Cache Panel to subdirectory * lint * refactor: add display names * fix: typo * release: v5.0.0-alpha.14 * fix(solid-query): SSR fixes - Inconsistent state (#5093) * fix(solid-query): do not call unsubscribe on the server * fix(solid-query): prefer val from queryResource if it is available there * chore: add hydration debugger to solid ssr example * bump minimum solid-js version * chore: pnpm i * chore: fix rollup babel typings Result of this change upstream that types the “targets” property -> https://github.com/DefinitelyTyped/DefinitelyTyped/pull/63927/files#diff-a4da813bfdc10bbb7d4d9ee9b811309e7e2a16c0484b9a334752db84be4b0f31 Signed-off-by: marbemac <marbemac@gmail.com> * replace void 0 Signed-off-by: marbemac <marbemac@gmail.com> * chore: remove uncessary onMount Signed-off-by: marbemac <marbemac@gmail.com> * chore: skip this onComputed on first render Signed-off-by: marbemac <marbemac@gmail.com> * fix: copy state properties over for ssr hydration Signed-off-by: marbemac <marbemac@gmail.com> --------- Signed-off-by: marbemac <marbemac@gmail.com> * release: v5.0.0-alpha.15 * fix(solid-query): Fix non hydrating queries (#5229) * release: v5.0.0-alpha.16 * release: v5.0.0-alpha.17 * docs(react): fix typo in TypeScript.md (#5239) Signed-off-by: Eng Zer Jun <engzerjun@gmail.com> * fix: do not mutate input (#5240) * fix: do not mutate input params passed to function from consumers should be treated as readonly and thus shouldn't be modified * test: remove unexpected `exact` props from find methods --------- Co-authored-by: Damian Osipiuk <osipiukd+git@gmail.com> * release: v5.0.0-alpha.18 * docs: update migrating-to-v5 (#5274) I think the rocket emoji is causing a visual bug too but since I edited this through GitHub's UI, I couldn't confirm. * fix(query-core): correct placeholderData prevData value with select fn (#5227) * fix(query-core): correct placeholderData prevData * fix(query-core): preserves correct prevQueryResult This commit preserves the correct previous result between rerenders. * test(react-query): Test with placeholder & select * fix(query-core): Add lastDefinedQueryData property * fix(query-core): Remove console.log * fix(query-core): Add react-query test * release: v5.0.0-alpha.19 * feat(solid-query): Add `reconcile` option (#5287) * feat(solid-query): Add `reconcile` option * feat(solid-query): Add `reconcile` callback test * release: v5.0.0-alpha.20 * chore: adapt tests to v5 syntax after merge * feat: remove callbacks from QueryObserver (#5282) * feat: remove callbacks from QueryObserver types are passing now * test: remove some more callback related tests * docs: migration guide for removed callbacks * chore: fix broken lock file * chore: remove unused variables those were only needed on main for keepPreviousData, which doesn't exist anymore * release: v5.0.0-alpha.21 * fix(solid-query): Remove unserializable values (#5326) * release: v5.0.0-alpha.22 * feat: rename throwErrors to throwOnError (#5318) * feat: rename throwErrors to throwOnError to be aligned with the options we already have on imperative methods, like `invalidateQueries` * docs: fix outdated code reference * chore: rename type * fix: let the refetchInterval function also return undefined and fall back to false if it does * release: v5.0.0-alpha.23 * docs: remove duplicated `isInitialLoading` (#5327) * fix: make sure codemods are included in react-query (#5340) * chore: fix pr pipeline (#5345) * chore: remove unneeded script * chore: fix syntax error after merging * Empty-Commit * chore: update to node18 to hopefully fix CI issues see: https://github.com/vitest-dev/vitest/issues/1191#issuecomment-1192798501 * chore: don't throw error if build dir already exists * release: v5.0.0-alpha.24 * feat: queryOptions helper function (#5153) * feat: queryOptions helper function so that we can define and share options outside of useQuery, but still get the type inference * docs: queryOptions * docs: remove reference to onError * docs: update migration guide * release: v5.0.0-alpha.25 * chore: remove createStore option (#5352) having the option to customize the internal store sound nice, but the problem is that the store holds Query instances, not data. So, the setter is only called once, not on every data update. This makes it relatively useless - every time we thought we could leverage createStore, it fell short of our requirements because of this. The better way is usually to subscribe to the QueryCache directly * docs: remove callbacks from useQuery * fix(core): make sure refetching multiple queries imperatively works offline (#5249) * fix(core): make sure refetching multiple queries imperatively works offline * test: add another test for different networkMode * fix: always catch promises even if we don't return them because we are offline * release: v5.0.0-alpha.26 * chore: svelte-query tests, validatePackages changes * feat(devtools): Add framework agnostic devtools (#5347) * feat(devtools): Add framework agnostic devtools draft * Fix test * Move query-devtools build before react-query-devtools * Fix dimensions bug & add isInitialOpen props * Fix isOpen state * Add devtools cutom errorTypes option * Add explicit close button * Add keyboard focus for tooltips * Add query-core to query-devtools peerDependencies * Update pnpm lock file * Add overflow hidden to hide filters on top view * Revert overflow hidden - causing other issues * Update documentation * Fix validate-packages script --------- Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * fix(query-devtools): Add query-core to devDependencies (#5360) * fix(query-devtools): Add query-core to devDependencies * Fix pnpm-lock.yaml * release: v5.0.0-alpha.27 * feat(solid-query): `queryOptions` helper for solid-query (#5355) * feat: queryOptions helper for solid-query * add tests * fix imports * release: v5.0.0-alpha.28 * feat(svelte-query-devtools): Svelte Adapter for new Devtools (#5362) * Implement working devtools component * Fix pnpm-lock.yaml * Update workspace config * Always a prettier error * Fix eslint error * Fix test:types * Add svelte-query to deps * Use esm-env to block loading in prod * Remove example changes * Simpler export * Allow dynamically editing props * Run prettier * fix(devtools): Update ESM export extension (#5364) * fix(devtools): Update ESM export extension * Update Svelte devtools types error * Fix svelte-query-devtools types error * release: v5.0.0-alpha.29 * feat(devtools): Make queryclient reactive (#5366) * release: v5.0.0-alpha.30 * Revert changes to svelte-query build * fix(svelte-query-devtools): Fix tsconfig paths * fix(svelte-query-devtools): Fix issue parsing JSX (#5372) * feat(query-core): Add previousQuery to placeholderFn (#5358) * feat(query-core): Add previousQuery to placeholderFn * Add query-core and react-query tests * Remove unused query type --------- Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * release: v5.0.0-alpha.31 * docs: Update dependent-queries.md (#5391) I believe `isLoading` has been renamed to `isPending` * refactor: unwrap listeners * chore: relax eslint for tests * release: v5.0.0-alpha.32 * docs: new docs for placeholderData * feat(useQueries): combine (#5219) * attempt at adding combine on observer level (doesn't work) * feat(useQueries): combine adapt getOptimisticResult to return both the result array and a combined result getter * feat(useQueries): combine make sure combinedResult stays in sync with result * feat(vue-query): combine results for useQueries hook * Add new options to svelte-query * Add new options to solid-query * fix: enable property tracking for useQueries * fix: move property tracking to react layer * chore: remove logging * chore: remove unnecessary type assertion * test: tests for combined data * docs: combine --------- Co-authored-by: Damian Osipiuk <osipiukd+git@gmail.com> Co-authored-by: Lachlan Collins <1667261+lachlancollins@users.noreply.github.com> Co-authored-by: Aryan Deora <adeora@iu.edu> * docs: combine * chore: setup fallback base to origin/main if we trigger a release manually via github, this value might not be filled * release: v5.0.0-alpha.34 * docs: update installation * chore: Improve eslint/tsconfig setup in svelte packages (#5438) * fix(types): fix TError generic on queryOptions * release: v5.0.0-alpha.35 * release: v5.0.0-alpha.36 * chore: Bump eslint version to 8.34.0 (#5439) * feat(svelte-query): Simplify types (#5442) * release: v5.0.0-alpha.37 * chore: Update dev dependencies (#5466) * chore: Replace cp with cpy-cli (#5441) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * fix: Update typescript-eslint (#5467) * release: v5.0.0-alpha.38 * chore: More package updates (#5468) * chore: Link examples to workspace packages (#5469) * feat(svelte-query): Switch to moduleResolution bundler (#5471) * fix: Downgrade chalk to v4 (#5472) * release: v5.0.0-alpha.39 * docs: change Hydrate->HydrationBoundary (#5455) * updated docs on SSR Hydrate -> HydrationBoundary * docs(ssr): change Hydrate->HydrationBoundary change Hydrate->HydrationBoundary to remove deprecated component * docs(ssr): rename all Hydrate->HydrationBoundary rename all Hydrate instances ->HydrationBoundary for consistency * feat(react-query-persist-client): await onuccess (#5473) * fix: have `onSuccess` return a promise too so that we can await it that way, invalidation or mutations that run in onSuccess will still keep isRestoring to be false, which avoids race conditions * test: test for awaiting onSuccess * docs: onSuccess * release: v5.0.0-alpha.40 * release: v5.0.0-alpha.41 * chore: Regenerate alpha lockfile (#5477) * docs(solid-query): Fix API signature in overview.md (#5470) * docs(svelte-query): Add svelte-query-devtools to examples (#5478) * chore: Clean-up eslint config (#5481) * chore: More eslint improvements (#5482) * feat: Convert rollup config to ESM (#5484) * chore: Migrate scripts to ESM (#5486) * feat: Split rollup config for Nx caching (#5487) * fix: Fix CJS/ESM issue with @commitlint/parse I can't believe these issues still exist, see https://github.com/evanw/esbuild/issues/1719 * chore: Update prettier, eslint, rollup, scripts (#5490) * chore: Fix prettierignore * release: v5.0.0-alpha.42 * fix: Update @commitlint/parse (#5491) See https://github.com/conventional-changelog/commitlint/pull/3614 * release: v5.0.0-alpha.43 * chore: Add eslint-plugin-compat (#5495) * Fix workspace links * Add eslint-plugin-compat * Update nx.json * fix: Improve workspace tsconfig (#5497) * release: v5.0.0-alpha.44 * fix: Move deps/devDeps/peerDeps to appropriate location (#5498) * chore: Extend base tsconfig for svelte packages (#5501) * release: v5.0.0-alpha.45 * chore: Make test:types have no Nx output (#5500) * feat: Remove svelte field from package.json (#5504) * release: v5.0.0-alpha.46 * feat: Add explicit package.json `type` field (#5505) * release: v5.0.0-alpha.47 * chore: Fix nx affected (#5509) * fix: Fix ESLint warnings (#5510) * release: v5.0.0-alpha.48 * chore: Update to Nx 16.3.1 (#5514) * chore: Update to nx 16.3.1 * Update pnpm-lock.yaml * chore: Update Nx cloud workflow (#5515) * feat: Drop legacy webpack v4 support (#5507) * release: v5.0.0-alpha.49 * feat: Remove UMD build output (#5517) * release: v5.0.0-alpha.50 * chore: Rework rollup externals (#5519) * feat: Refactor package exports (#5520) * chore: Remove publint error temporarily * release: v5.0.0-alpha.51 * fix: Publint error in solid-query (#5522) * release: v5.0.0-alpha.52 * fix: Simplify exports in solidjs packages (#5523) * release: v5.0.0-alpha.53 * chore: Improve Nx task separation (#5524) * Fix ci workflow nx run-many doesn't use --base * feat(query-devtools): Lazyload Query Devtools Core (#5527) * release: v5.0.0-alpha.54 * fix(query-devtools): Broken package.json exports (#5528) * Make publint throw errors * Rewrite CJS files to use .cjs extension * Add concurrency option to PR workflow * Fix export extensions * release: v5.0.0-alpha.55 * chore: Re-enable Nx Distributed Task Execution (#5518) * fix(query-devtools): inform onlineManager when offline mode is simulated (#5534) * release: v5.0.0-alpha.56 * docs: make returning a promise for optimistic updates more explicit (#5485) * fix(codemod): do not mark the `buildMessage` method as private (#5546) * fix(codemod): do not mark the `buildMessage` method as private It might fail because of the lack of support. * chore(codemod): add missing `filePath` parameter to the docblock * release: v5.0.0-alpha.57 * fix(query-devtools): Fix getSidedProp bug (#5551) * release: v5.0.0-alpha.58 * chore: Update publish script (#5559) * fix(query-devtools): Add chunkFileNames option (#5560) * release: v5.0.0-alpha.59 * fix: Change `svelte-package` output directory (#5561) * release: v5.0.0-alpha.60 * release: v5.0.0-alpha.61 * chore: try to stabilize test * fix(solid-query): Use rollup-preset-solid (#5565) * release: v5.0.0-alpha.62 * feat: Add legacy rollup builds (#5570) * release: v5.0.0-alpha.63 * docs: Add `"private": true` to examples (#5578) * release: v5.0.0-alpha.64 * fix(useIsMutating): fix vue warning (#5453) onScopeDispose() is called when there is no active effect scope to be associated with * release: v5.0.0-alpha.65 * feat(infiniteQuery): allow prefetching arbitrary amounts of pages (#5440) * refactor: combine fetching first page with refetching as it's the same condition * feat(infiniteQuery): allow prefetching arbitrary amounts of pages * test prefetching * fix: make sure that pages and getNextPageParam are passed in tandem to (pre)fetchInfiniteQuery * docs: prefetching * chore: try to stabilize test * docs: migration guide * release: v5.0.0-alpha.66 * refactor: move queryOptions to its own file (#5480) * refactor: remove 'use client' from non-components * refactor: move queryOptions to its own file where we don't have a 'use client' directive, because we can call this function on the server as well * Revert "refactor: remove 'use client' from non-components" This reverts commit 8ecac6688b01197c4c4010d3e240dfbca1895d50. * refactor: rename isRestoring file * chore: fix import * release: v5.0.0-alpha.67 * fix: Update eslint-plugin-query build config (#5601) * fix: Use pnpm workspace protocol (#5600) * release: v5.0.0-alpha.68 * chore: Use nx watch command (#5605) * fix(solid-query): revert package.json typo (#5615) * release: v5.0.0-alpha.69 * release: v5.0.0-alpha.70 * release: v5.0.0-alpha.71 * chore: Fix Nx parallelisation for vue-query tests (#5635) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * fix(devtools): padding for action buttons (#5608) global `button` styles would otherwise affect buttons * release: v5.0.0-alpha.72 * feat: Support Svelte v4 (#5659) * feat: Support svelte v4 * Downgrade @testing-library/svelte * Upgrade @testing-library/svelte to 4.0.3 * Refactor onMount dynamic import * release: v5.0.0-alpha.73 * fix(eslint-plugin-query): Use tsup to generate types (#5666) * release: v5.0.0-alpha.74 * fix: Skip queryClient context lookup if client passed directly (#5669) * release: v5.0.0-alpha.75 * feat: Accept all svelte stores as options (#5672) * refactor: Accept stores other than writable * Cleanup Readable type import * Add tests * Stricter isSvelteStore check * Update docs * Fix input bind * Add testing-library cleanup * release: v5.0.0-alpha.76 * fix(svelte-query): Fix staleTime reactivity bug (#5682) * release: v5.0.0-alpha.77 * chore(svelte-query): Update reactivity docs and tests (#5683) * fix(query-devtools): Bundle all dependencies (#5684) * release: v5.0.0-alpha.78 * release: v5.0.0-alpha.79 * feat: react-query-next-experimental package (#5598) * chore: fix a copy-paste error * chore: bootstrap package * chore: setup package * chore: allow passing with no tests * fix: remove 'use client' from index bundle * chore: cleanup copy/paste error * chore: fix prettier * refactor: replace ref with direct props access * fix: do not write to refs during render * refactor: inline function into useEffect to avoid useCallback * fix: eslint no-shadow * refactor: namespace id * refactor: removed pointless check * fix: set to empty array on cleanup * fix: adapt for v5 changes * chore: fix build * docs: add streaming example * chore: fix outdated lockfile * chore: fix prettier * refactor: remove isSubscribed ref * refactor: re-arrange comment * chore: remove comments * chore: fix broken lock file * feat: allow customization of hydrate / dehydrate options and make sure we fall back to the defaultShouldDehydrate function, which only dehydrates successful queries * release: v5.0.0-alpha.80 * docs: fix nextjs-streaming example * fix(core) : sync Observer 'current' properties when optimistic reading occurs (#5611) * fix-5538 : sync Observer 'current' properties when optimistic reading occurs * Flip test on currentResult with placeholderData's order & add test * Fix tests using the same queryKey * remove options.placeHolderData from deciding whether to assign observer current properties, use equalitycheck on v5 * maybe fix for vue reactivity cbs * test(vue-query): test persister with useQuery * Force line terminator to \\n on codemods tests * Revert " Force line terminator to \\n on codemods tests" This reverts commit 6f0a469f51e162052ea3245b4ef3da7c6febc9c3. --------- Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Damian Osipiuk <osipiukd+git@gmail.com> * chore: Force line terminator to \\n on codemods tests (#5664) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: stabilize a flaky test * release: v5.0.0-alpha.81 * docs: remove devtools from example because they currently don't work * fix(query-devtools): Force publish package (#5715) * release: v5.0.0-alpha.82 * docs: re-enable devtools * fix: Update dev dependencies (#5718) * release: v5.0.0-alpha.83 * chore: Add vite to root package.json (#5722) * refactor: Add new eslint sorting from main (#5723) * release: v5.0.0-alpha.84 * chore: Update vite and vitest (#5724) * chore: Remove eslint-plugin-compat (#5732) * feat: include meta in query and mutation hydration (#5733) * feat: include `meta` in query and mutation hydration * test: tests for meta hydration * chore: stabilize a flaky test * chore: stabilize another flaky test * release: v5.0.0-alpha.85 * fix(onlineManager): always initialize with `online: true` (#5714) * fix(onlineManager): always initialize with `online: true` instead of relying on navigator.onLine, because that indicator is broken AF in chrome https://bugs.chromium.org/p/chromium/issues/list?q=navigator.online * docs: document subscribe methods * docs * test: fix types in tests setting to undefined is now illegal, so we have to reset to `true`, which is the default now * fix(tests): switch from mocking navigator.onLine to mocking onlineManager.isOnline * fix: offline toggle in devtools it should now be enough to set online to true / false, without firing the event, because we always set & respect that value. we don't override the event handler, so real online / offline events might interfere here * chore: fix tests with the implementation of onlineManager, where we default to `true`, we need an explicit `'offline'` event to get it to false; otherwise, switching back to true doesn't change the state, so subscribers are not informed * chore: prettier write * chore: fix eslint * chore: delete an old, flaky test that doesn't test much * release: v5.0.0-alpha.86 * docs: use bundlejs for bundle-size * docs: fix link * feat: Replace rollup with tsup/esbuild (#5597) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Aryan Deora <adeora@iu.edu> * release: v5.0.0-alpha.87 * chore: Simplify tsconfig (#5745) * fix: Simplify devDependencies (#5747) * fix: Fix tsconfig "include" setting (#5750) * release: v5.0.0-alpha.88 * docs: fix potential typo (#5748) * fix potential typo * Update docs/react/guides/queries.md --------- Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * fix: Add missing extensions to ESM imports (#5751) * chore: Bundler integration tests (#5756) * Add react-cra5 test * Add react-cra4 test * Add react-vite test * Add svelte-vite test * Add solid-vite test * Run prettier * Rename script to test:bundle * Add vue-vite test * Run prettier * fix(query-devtools): Fix Devtools Build Issues (#5768) * release: v5.0.0-alpha.89 * feat(codemod): add codemod that renames the `Hydrate` component usages to `HydrationBoundary` usages (#5761) * feat(codemod): add codemod that renames the `cacheTime` and `useErrorBoundary` object properties and TypeScript property signatures (#5765) * feat(react-query): useSuspenseQuery (#5739) * feat: useSuspenseQuery * feat: infiniteQueryOptions * fix: add exports * feat: useSuspenseInfiniteQuery * feat: initialData overloads for useInfiniteQuery * fix: types * chore: stabilize test we sometimes get failureCount: 2, but it doesn't matter here (timing issue) * fix: types for useSuspenseQuery (#5755) * docs: suspense * docs: api reference * docs: useSuspenseQuery in examples * fix: types for useSuspenseInfiniteQuery (#5766) --------- Co-authored-by: Jonghyeon Ko <manudeli.ko@gmail.com> * release: v5.0.0-alpha.90 * chore: fix prettier * chore: fix tests * release: v5.0.0-alpha.91 --------- Signed-off-by: marbemac <marbemac@gmail.com> Signed-off-by: Eng Zer Jun <engzerjun@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@users.noreply.github.com> Co-authored-by: Fredrik Höglund <fredrik.hoglund@gmail.com> Co-authored-by: Gabriel Pichot <gabriel.pichot@gmail.com> Co-authored-by: Marc MacLeod <marbemac@gmail.com> Co-authored-by: Aryan Deora <adeora@iu.edu> Co-authored-by: Eng Zer Jun <engzerjun@gmail.com> Co-authored-by: Damian Osipiuk <osipiukd+git@gmail.com> Co-authored-by: Arthur Denner <arthurdenner7@gmail.com> Co-authored-by: Ilya <marchukilya@gmail.com> Co-authored-by: Lachlan Collins <1667261+lachlancollins@users.noreply.github.com> Co-authored-by: OrJDev <91349014+OrJDev@users.noreply.github.com> Co-authored-by: Enguerrand des Vaux <enguerrand@des-vaux.fr> Co-authored-by: Dennis kinuthia <denniskinuthiaw@gmail.com> Co-authored-by: Yuji Sugiura <leader22@users.noreply.github.com> Co-authored-by: Yaroslav Lapin <jlarky@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Aleksandr Semenov <juvirez@gmail.com> Co-authored-by: Matthew Salsamendi <matthewsalsamendi@gmail.com> Co-authored-by: Speros Kokenes <skokenes@users.noreply.github.com> Co-authored-by: EL AYADI Mohamed <moh.el.ayadi@gmail.com> Co-authored-by: Dale Seo <5466341+DaleSeo@users.noreply.github.com> Co-authored-by: Jonghyeon Ko <manudeli.ko@gmail.com>
2023-07-24 11:59:07 +02:00
`setQueryData` is a synchronous function that can be used to immediately update a query's cached data. If the query does not exist, it will be created. **If the query is not utilized by a query hook in the default `gcTime` of 5 minutes, the query will be garbage collected**. To update multiple queries at once and match query keys partially, you need to use [`queryClient.setQueriesData`](#queryclientsetqueriesdata) instead.
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
> The difference between using `setQueryData` and `fetchQuery` is that `setQueryData` is sync and assumes that you already synchronously have the data available. If you need to fetch the data asynchronously, it's suggested that you either refetch the query key or use `fetchQuery` to handle the asynchronous fetch.
```tsx
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
queryClient.setQueryData(queryKey, updater)
```
**Options**
- `queryKey: QueryKey`: [Query Keys](../framework/react/guides/query-keys.md)
- `updater: TQueryFnData | undefined | ((oldData: TQueryFnData | undefined) => TQueryFnData | undefined)`
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
- If non-function is passed, the data will be updated to this value
- If a function is passed, it will receive the old data value and be expected to return a new one.
**Using an updater value**
```tsx
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
setQueryData(queryKey, newData)
```
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
If the value is `undefined`, the query data is not updated.
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
**Using an updater function**
For convenience in syntax, you can also pass an updater function which receives the current data value and returns the new one:
```tsx
setQueryData(queryKey, (oldData) => newData)
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
```
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
If the updater function returns `undefined`, the query data will not be updated. If the updater function receives `undefined` as input, you can return `undefined` to bail out of the update and thus _not_ create a new cache entry.
2022-11-08 12:07:27 +01:00
**Immutability**
Updates via `setQueryData` must be performed in an _immutable_ way. **DO NOT** attempt to write directly to the cache by mutating `oldData` or data that you retrieved via `getQueryData` in place.
2022-11-08 12:07:27 +01:00
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
## `queryClient.getQueryState`
`getQueryState` is a synchronous function that can be used to get an existing query's state. If the query does not exist, `undefined` will be returned.
```tsx
feat: beta release (#5771) * release: v5.0.0-alpha.11 * refactor(core): unify hydration options (#5131) * refactor: unify hydration options * docs: update hydration docs * migration guide * refactor: use shouldDehydrate... syntax * Update docs/react/guides/migrating-to-v5.md Co-authored-by: Fredrik Höglund <fredrik.hoglund@gmail.com> * Apply suggestions from code review * chore: fix tests * chore: fix tests * Update docs/react/reference/hydration.md --------- Co-authored-by: Fredrik Höglund <fredrik.hoglund@gmail.com> * release: v5.0.0-alpha.12 * release: v5.0.0-alpha.13 * chore: remove unused devDependencies (#5211) * refactor(react-query-devtools): move devtools components in files (#5150) * refactor(react-query-devtools): move QueryStatusCount header to subdirectory * refactor(react-query-devtools): move QueryRow to subdirectory * refactor(react-query-devtools): move ActiveQuery to subdirectory * refactor(react-query-devtools): move Cache Panel to subdirectory * lint * refactor: add display names * fix: typo * release: v5.0.0-alpha.14 * fix(solid-query): SSR fixes - Inconsistent state (#5093) * fix(solid-query): do not call unsubscribe on the server * fix(solid-query): prefer val from queryResource if it is available there * chore: add hydration debugger to solid ssr example * bump minimum solid-js version * chore: pnpm i * chore: fix rollup babel typings Result of this change upstream that types the “targets” property -> https://github.com/DefinitelyTyped/DefinitelyTyped/pull/63927/files#diff-a4da813bfdc10bbb7d4d9ee9b811309e7e2a16c0484b9a334752db84be4b0f31 Signed-off-by: marbemac <marbemac@gmail.com> * replace void 0 Signed-off-by: marbemac <marbemac@gmail.com> * chore: remove uncessary onMount Signed-off-by: marbemac <marbemac@gmail.com> * chore: skip this onComputed on first render Signed-off-by: marbemac <marbemac@gmail.com> * fix: copy state properties over for ssr hydration Signed-off-by: marbemac <marbemac@gmail.com> --------- Signed-off-by: marbemac <marbemac@gmail.com> * release: v5.0.0-alpha.15 * fix(solid-query): Fix non hydrating queries (#5229) * release: v5.0.0-alpha.16 * release: v5.0.0-alpha.17 * docs(react): fix typo in TypeScript.md (#5239) Signed-off-by: Eng Zer Jun <engzerjun@gmail.com> * fix: do not mutate input (#5240) * fix: do not mutate input params passed to function from consumers should be treated as readonly and thus shouldn't be modified * test: remove unexpected `exact` props from find methods --------- Co-authored-by: Damian Osipiuk <osipiukd+git@gmail.com> * release: v5.0.0-alpha.18 * docs: update migrating-to-v5 (#5274) I think the rocket emoji is causing a visual bug too but since I edited this through GitHub's UI, I couldn't confirm. * fix(query-core): correct placeholderData prevData value with select fn (#5227) * fix(query-core): correct placeholderData prevData * fix(query-core): preserves correct prevQueryResult This commit preserves the correct previous result between rerenders. * test(react-query): Test with placeholder & select * fix(query-core): Add lastDefinedQueryData property * fix(query-core): Remove console.log * fix(query-core): Add react-query test * release: v5.0.0-alpha.19 * feat(solid-query): Add `reconcile` option (#5287) * feat(solid-query): Add `reconcile` option * feat(solid-query): Add `reconcile` callback test * release: v5.0.0-alpha.20 * chore: adapt tests to v5 syntax after merge * feat: remove callbacks from QueryObserver (#5282) * feat: remove callbacks from QueryObserver types are passing now * test: remove some more callback related tests * docs: migration guide for removed callbacks * chore: fix broken lock file * chore: remove unused variables those were only needed on main for keepPreviousData, which doesn't exist anymore * release: v5.0.0-alpha.21 * fix(solid-query): Remove unserializable values (#5326) * release: v5.0.0-alpha.22 * feat: rename throwErrors to throwOnError (#5318) * feat: rename throwErrors to throwOnError to be aligned with the options we already have on imperative methods, like `invalidateQueries` * docs: fix outdated code reference * chore: rename type * fix: let the refetchInterval function also return undefined and fall back to false if it does * release: v5.0.0-alpha.23 * docs: remove duplicated `isInitialLoading` (#5327) * fix: make sure codemods are included in react-query (#5340) * chore: fix pr pipeline (#5345) * chore: remove unneeded script * chore: fix syntax error after merging * Empty-Commit * chore: update to node18 to hopefully fix CI issues see: https://github.com/vitest-dev/vitest/issues/1191#issuecomment-1192798501 * chore: don't throw error if build dir already exists * release: v5.0.0-alpha.24 * feat: queryOptions helper function (#5153) * feat: queryOptions helper function so that we can define and share options outside of useQuery, but still get the type inference * docs: queryOptions * docs: remove reference to onError * docs: update migration guide * release: v5.0.0-alpha.25 * chore: remove createStore option (#5352) having the option to customize the internal store sound nice, but the problem is that the store holds Query instances, not data. So, the setter is only called once, not on every data update. This makes it relatively useless - every time we thought we could leverage createStore, it fell short of our requirements because of this. The better way is usually to subscribe to the QueryCache directly * docs: remove callbacks from useQuery * fix(core): make sure refetching multiple queries imperatively works offline (#5249) * fix(core): make sure refetching multiple queries imperatively works offline * test: add another test for different networkMode * fix: always catch promises even if we don't return them because we are offline * release: v5.0.0-alpha.26 * chore: svelte-query tests, validatePackages changes * feat(devtools): Add framework agnostic devtools (#5347) * feat(devtools): Add framework agnostic devtools draft * Fix test * Move query-devtools build before react-query-devtools * Fix dimensions bug & add isInitialOpen props * Fix isOpen state * Add devtools cutom errorTypes option * Add explicit close button * Add keyboard focus for tooltips * Add query-core to query-devtools peerDependencies * Update pnpm lock file * Add overflow hidden to hide filters on top view * Revert overflow hidden - causing other issues * Update documentation * Fix validate-packages script --------- Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * fix(query-devtools): Add query-core to devDependencies (#5360) * fix(query-devtools): Add query-core to devDependencies * Fix pnpm-lock.yaml * release: v5.0.0-alpha.27 * feat(solid-query): `queryOptions` helper for solid-query (#5355) * feat: queryOptions helper for solid-query * add tests * fix imports * release: v5.0.0-alpha.28 * feat(svelte-query-devtools): Svelte Adapter for new Devtools (#5362) * Implement working devtools component * Fix pnpm-lock.yaml * Update workspace config * Always a prettier error * Fix eslint error * Fix test:types * Add svelte-query to deps * Use esm-env to block loading in prod * Remove example changes * Simpler export * Allow dynamically editing props * Run prettier * fix(devtools): Update ESM export extension (#5364) * fix(devtools): Update ESM export extension * Update Svelte devtools types error * Fix svelte-query-devtools types error * release: v5.0.0-alpha.29 * feat(devtools): Make queryclient reactive (#5366) * release: v5.0.0-alpha.30 * Revert changes to svelte-query build * fix(svelte-query-devtools): Fix tsconfig paths * fix(svelte-query-devtools): Fix issue parsing JSX (#5372) * feat(query-core): Add previousQuery to placeholderFn (#5358) * feat(query-core): Add previousQuery to placeholderFn * Add query-core and react-query tests * Remove unused query type --------- Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * release: v5.0.0-alpha.31 * docs: Update dependent-queries.md (#5391) I believe `isLoading` has been renamed to `isPending` * refactor: unwrap listeners * chore: relax eslint for tests * release: v5.0.0-alpha.32 * docs: new docs for placeholderData * feat(useQueries): combine (#5219) * attempt at adding combine on observer level (doesn't work) * feat(useQueries): combine adapt getOptimisticResult to return both the result array and a combined result getter * feat(useQueries): combine make sure combinedResult stays in sync with result * feat(vue-query): combine results for useQueries hook * Add new options to svelte-query * Add new options to solid-query * fix: enable property tracking for useQueries * fix: move property tracking to react layer * chore: remove logging * chore: remove unnecessary type assertion * test: tests for combined data * docs: combine --------- Co-authored-by: Damian Osipiuk <osipiukd+git@gmail.com> Co-authored-by: Lachlan Collins <1667261+lachlancollins@users.noreply.github.com> Co-authored-by: Aryan Deora <adeora@iu.edu> * docs: combine * chore: setup fallback base to origin/main if we trigger a release manually via github, this value might not be filled * release: v5.0.0-alpha.34 * docs: update installation * chore: Improve eslint/tsconfig setup in svelte packages (#5438) * fix(types): fix TError generic on queryOptions * release: v5.0.0-alpha.35 * release: v5.0.0-alpha.36 * chore: Bump eslint version to 8.34.0 (#5439) * feat(svelte-query): Simplify types (#5442) * release: v5.0.0-alpha.37 * chore: Update dev dependencies (#5466) * chore: Replace cp with cpy-cli (#5441) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * fix: Update typescript-eslint (#5467) * release: v5.0.0-alpha.38 * chore: More package updates (#5468) * chore: Link examples to workspace packages (#5469) * feat(svelte-query): Switch to moduleResolution bundler (#5471) * fix: Downgrade chalk to v4 (#5472) * release: v5.0.0-alpha.39 * docs: change Hydrate->HydrationBoundary (#5455) * updated docs on SSR Hydrate -> HydrationBoundary * docs(ssr): change Hydrate->HydrationBoundary change Hydrate->HydrationBoundary to remove deprecated component * docs(ssr): rename all Hydrate->HydrationBoundary rename all Hydrate instances ->HydrationBoundary for consistency * feat(react-query-persist-client): await onuccess (#5473) * fix: have `onSuccess` return a promise too so that we can await it that way, invalidation or mutations that run in onSuccess will still keep isRestoring to be false, which avoids race conditions * test: test for awaiting onSuccess * docs: onSuccess * release: v5.0.0-alpha.40 * release: v5.0.0-alpha.41 * chore: Regenerate alpha lockfile (#5477) * docs(solid-query): Fix API signature in overview.md (#5470) * docs(svelte-query): Add svelte-query-devtools to examples (#5478) * chore: Clean-up eslint config (#5481) * chore: More eslint improvements (#5482) * feat: Convert rollup config to ESM (#5484) * chore: Migrate scripts to ESM (#5486) * feat: Split rollup config for Nx caching (#5487) * fix: Fix CJS/ESM issue with @commitlint/parse I can't believe these issues still exist, see https://github.com/evanw/esbuild/issues/1719 * chore: Update prettier, eslint, rollup, scripts (#5490) * chore: Fix prettierignore * release: v5.0.0-alpha.42 * fix: Update @commitlint/parse (#5491) See https://github.com/conventional-changelog/commitlint/pull/3614 * release: v5.0.0-alpha.43 * chore: Add eslint-plugin-compat (#5495) * Fix workspace links * Add eslint-plugin-compat * Update nx.json * fix: Improve workspace tsconfig (#5497) * release: v5.0.0-alpha.44 * fix: Move deps/devDeps/peerDeps to appropriate location (#5498) * chore: Extend base tsconfig for svelte packages (#5501) * release: v5.0.0-alpha.45 * chore: Make test:types have no Nx output (#5500) * feat: Remove svelte field from package.json (#5504) * release: v5.0.0-alpha.46 * feat: Add explicit package.json `type` field (#5505) * release: v5.0.0-alpha.47 * chore: Fix nx affected (#5509) * fix: Fix ESLint warnings (#5510) * release: v5.0.0-alpha.48 * chore: Update to Nx 16.3.1 (#5514) * chore: Update to nx 16.3.1 * Update pnpm-lock.yaml * chore: Update Nx cloud workflow (#5515) * feat: Drop legacy webpack v4 support (#5507) * release: v5.0.0-alpha.49 * feat: Remove UMD build output (#5517) * release: v5.0.0-alpha.50 * chore: Rework rollup externals (#5519) * feat: Refactor package exports (#5520) * chore: Remove publint error temporarily * release: v5.0.0-alpha.51 * fix: Publint error in solid-query (#5522) * release: v5.0.0-alpha.52 * fix: Simplify exports in solidjs packages (#5523) * release: v5.0.0-alpha.53 * chore: Improve Nx task separation (#5524) * Fix ci workflow nx run-many doesn't use --base * feat(query-devtools): Lazyload Query Devtools Core (#5527) * release: v5.0.0-alpha.54 * fix(query-devtools): Broken package.json exports (#5528) * Make publint throw errors * Rewrite CJS files to use .cjs extension * Add concurrency option to PR workflow * Fix export extensions * release: v5.0.0-alpha.55 * chore: Re-enable Nx Distributed Task Execution (#5518) * fix(query-devtools): inform onlineManager when offline mode is simulated (#5534) * release: v5.0.0-alpha.56 * docs: make returning a promise for optimistic updates more explicit (#5485) * fix(codemod): do not mark the `buildMessage` method as private (#5546) * fix(codemod): do not mark the `buildMessage` method as private It might fail because of the lack of support. * chore(codemod): add missing `filePath` parameter to the docblock * release: v5.0.0-alpha.57 * fix(query-devtools): Fix getSidedProp bug (#5551) * release: v5.0.0-alpha.58 * chore: Update publish script (#5559) * fix(query-devtools): Add chunkFileNames option (#5560) * release: v5.0.0-alpha.59 * fix: Change `svelte-package` output directory (#5561) * release: v5.0.0-alpha.60 * release: v5.0.0-alpha.61 * chore: try to stabilize test * fix(solid-query): Use rollup-preset-solid (#5565) * release: v5.0.0-alpha.62 * feat: Add legacy rollup builds (#5570) * release: v5.0.0-alpha.63 * docs: Add `"private": true` to examples (#5578) * release: v5.0.0-alpha.64 * fix(useIsMutating): fix vue warning (#5453) onScopeDispose() is called when there is no active effect scope to be associated with * release: v5.0.0-alpha.65 * feat(infiniteQuery): allow prefetching arbitrary amounts of pages (#5440) * refactor: combine fetching first page with refetching as it's the same condition * feat(infiniteQuery): allow prefetching arbitrary amounts of pages * test prefetching * fix: make sure that pages and getNextPageParam are passed in tandem to (pre)fetchInfiniteQuery * docs: prefetching * chore: try to stabilize test * docs: migration guide * release: v5.0.0-alpha.66 * refactor: move queryOptions to its own file (#5480) * refactor: remove 'use client' from non-components * refactor: move queryOptions to its own file where we don't have a 'use client' directive, because we can call this function on the server as well * Revert "refactor: remove 'use client' from non-components" This reverts commit 8ecac6688b01197c4c4010d3e240dfbca1895d50. * refactor: rename isRestoring file * chore: fix import * release: v5.0.0-alpha.67 * fix: Update eslint-plugin-query build config (#5601) * fix: Use pnpm workspace protocol (#5600) * release: v5.0.0-alpha.68 * chore: Use nx watch command (#5605) * fix(solid-query): revert package.json typo (#5615) * release: v5.0.0-alpha.69 * release: v5.0.0-alpha.70 * release: v5.0.0-alpha.71 * chore: Fix Nx parallelisation for vue-query tests (#5635) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * fix(devtools): padding for action buttons (#5608) global `button` styles would otherwise affect buttons * release: v5.0.0-alpha.72 * feat: Support Svelte v4 (#5659) * feat: Support svelte v4 * Downgrade @testing-library/svelte * Upgrade @testing-library/svelte to 4.0.3 * Refactor onMount dynamic import * release: v5.0.0-alpha.73 * fix(eslint-plugin-query): Use tsup to generate types (#5666) * release: v5.0.0-alpha.74 * fix: Skip queryClient context lookup if client passed directly (#5669) * release: v5.0.0-alpha.75 * feat: Accept all svelte stores as options (#5672) * refactor: Accept stores other than writable * Cleanup Readable type import * Add tests * Stricter isSvelteStore check * Update docs * Fix input bind * Add testing-library cleanup * release: v5.0.0-alpha.76 * fix(svelte-query): Fix staleTime reactivity bug (#5682) * release: v5.0.0-alpha.77 * chore(svelte-query): Update reactivity docs and tests (#5683) * fix(query-devtools): Bundle all dependencies (#5684) * release: v5.0.0-alpha.78 * release: v5.0.0-alpha.79 * feat: react-query-next-experimental package (#5598) * chore: fix a copy-paste error * chore: bootstrap package * chore: setup package * chore: allow passing with no tests * fix: remove 'use client' from index bundle * chore: cleanup copy/paste error * chore: fix prettier * refactor: replace ref with direct props access * fix: do not write to refs during render * refactor: inline function into useEffect to avoid useCallback * fix: eslint no-shadow * refactor: namespace id * refactor: removed pointless check * fix: set to empty array on cleanup * fix: adapt for v5 changes * chore: fix build * docs: add streaming example * chore: fix outdated lockfile * chore: fix prettier * refactor: remove isSubscribed ref * refactor: re-arrange comment * chore: remove comments * chore: fix broken lock file * feat: allow customization of hydrate / dehydrate options and make sure we fall back to the defaultShouldDehydrate function, which only dehydrates successful queries * release: v5.0.0-alpha.80 * docs: fix nextjs-streaming example * fix(core) : sync Observer 'current' properties when optimistic reading occurs (#5611) * fix-5538 : sync Observer 'current' properties when optimistic reading occurs * Flip test on currentResult with placeholderData's order & add test * Fix tests using the same queryKey * remove options.placeHolderData from deciding whether to assign observer current properties, use equalitycheck on v5 * maybe fix for vue reactivity cbs * test(vue-query): test persister with useQuery * Force line terminator to \\n on codemods tests * Revert " Force line terminator to \\n on codemods tests" This reverts commit 6f0a469f51e162052ea3245b4ef3da7c6febc9c3. --------- Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Damian Osipiuk <osipiukd+git@gmail.com> * chore: Force line terminator to \\n on codemods tests (#5664) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: stabilize a flaky test * release: v5.0.0-alpha.81 * docs: remove devtools from example because they currently don't work * fix(query-devtools): Force publish package (#5715) * release: v5.0.0-alpha.82 * docs: re-enable devtools * fix: Update dev dependencies (#5718) * release: v5.0.0-alpha.83 * chore: Add vite to root package.json (#5722) * refactor: Add new eslint sorting from main (#5723) * release: v5.0.0-alpha.84 * chore: Update vite and vitest (#5724) * chore: Remove eslint-plugin-compat (#5732) * feat: include meta in query and mutation hydration (#5733) * feat: include `meta` in query and mutation hydration * test: tests for meta hydration * chore: stabilize a flaky test * chore: stabilize another flaky test * release: v5.0.0-alpha.85 * fix(onlineManager): always initialize with `online: true` (#5714) * fix(onlineManager): always initialize with `online: true` instead of relying on navigator.onLine, because that indicator is broken AF in chrome https://bugs.chromium.org/p/chromium/issues/list?q=navigator.online * docs: document subscribe methods * docs * test: fix types in tests setting to undefined is now illegal, so we have to reset to `true`, which is the default now * fix(tests): switch from mocking navigator.onLine to mocking onlineManager.isOnline * fix: offline toggle in devtools it should now be enough to set online to true / false, without firing the event, because we always set & respect that value. we don't override the event handler, so real online / offline events might interfere here * chore: fix tests with the implementation of onlineManager, where we default to `true`, we need an explicit `'offline'` event to get it to false; otherwise, switching back to true doesn't change the state, so subscribers are not informed * chore: prettier write * chore: fix eslint * chore: delete an old, flaky test that doesn't test much * release: v5.0.0-alpha.86 * docs: use bundlejs for bundle-size * docs: fix link * feat: Replace rollup with tsup/esbuild (#5597) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Aryan Deora <adeora@iu.edu> * release: v5.0.0-alpha.87 * chore: Simplify tsconfig (#5745) * fix: Simplify devDependencies (#5747) * fix: Fix tsconfig "include" setting (#5750) * release: v5.0.0-alpha.88 * docs: fix potential typo (#5748) * fix potential typo * Update docs/react/guides/queries.md --------- Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * fix: Add missing extensions to ESM imports (#5751) * chore: Bundler integration tests (#5756) * Add react-cra5 test * Add react-cra4 test * Add react-vite test * Add svelte-vite test * Add solid-vite test * Run prettier * Rename script to test:bundle * Add vue-vite test * Run prettier * fix(query-devtools): Fix Devtools Build Issues (#5768) * release: v5.0.0-alpha.89 * feat(codemod): add codemod that renames the `Hydrate` component usages to `HydrationBoundary` usages (#5761) * feat(codemod): add codemod that renames the `cacheTime` and `useErrorBoundary` object properties and TypeScript property signatures (#5765) * feat(react-query): useSuspenseQuery (#5739) * feat: useSuspenseQuery * feat: infiniteQueryOptions * fix: add exports * feat: useSuspenseInfiniteQuery * feat: initialData overloads for useInfiniteQuery * fix: types * chore: stabilize test we sometimes get failureCount: 2, but it doesn't matter here (timing issue) * fix: types for useSuspenseQuery (#5755) * docs: suspense * docs: api reference * docs: useSuspenseQuery in examples * fix: types for useSuspenseInfiniteQuery (#5766) --------- Co-authored-by: Jonghyeon Ko <manudeli.ko@gmail.com> * release: v5.0.0-alpha.90 * chore: fix prettier * chore: fix tests * release: v5.0.0-alpha.91 --------- Signed-off-by: marbemac <marbemac@gmail.com> Signed-off-by: Eng Zer Jun <engzerjun@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@users.noreply.github.com> Co-authored-by: Fredrik Höglund <fredrik.hoglund@gmail.com> Co-authored-by: Gabriel Pichot <gabriel.pichot@gmail.com> Co-authored-by: Marc MacLeod <marbemac@gmail.com> Co-authored-by: Aryan Deora <adeora@iu.edu> Co-authored-by: Eng Zer Jun <engzerjun@gmail.com> Co-authored-by: Damian Osipiuk <osipiukd+git@gmail.com> Co-authored-by: Arthur Denner <arthurdenner7@gmail.com> Co-authored-by: Ilya <marchukilya@gmail.com> Co-authored-by: Lachlan Collins <1667261+lachlancollins@users.noreply.github.com> Co-authored-by: OrJDev <91349014+OrJDev@users.noreply.github.com> Co-authored-by: Enguerrand des Vaux <enguerrand@des-vaux.fr> Co-authored-by: Dennis kinuthia <denniskinuthiaw@gmail.com> Co-authored-by: Yuji Sugiura <leader22@users.noreply.github.com> Co-authored-by: Yaroslav Lapin <jlarky@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Aleksandr Semenov <juvirez@gmail.com> Co-authored-by: Matthew Salsamendi <matthewsalsamendi@gmail.com> Co-authored-by: Speros Kokenes <skokenes@users.noreply.github.com> Co-authored-by: EL AYADI Mohamed <moh.el.ayadi@gmail.com> Co-authored-by: Dale Seo <5466341+DaleSeo@users.noreply.github.com> Co-authored-by: Jonghyeon Ko <manudeli.ko@gmail.com>
2023-07-24 11:59:07 +02:00
const state = queryClient.getQueryState(queryKey)
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
console.log(state.dataUpdatedAt)
```
**Options**
- `queryKey: QueryKey`: [Query Keys](../framework/react/guides/query-keys.md)
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
## `queryClient.setQueriesData`
`setQueriesData` is a synchronous function that can be used to immediately update cached data of multiple queries by using filter function or partially matching the query key. Only queries that match the passed queryKey or queryFilter will be updated - no new cache entries will be created. Under the hood, [`setQueryData`](#queryclientsetquerydata) is called for each existing query.
```tsx
queryClient.setQueriesData(filters, updater)
```
**Options**
- `filters: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
- if a filter is passed, queryKeys matching the filter will be updated
- `updater: TQueryFnData | (oldData: TQueryFnData | undefined) => TQueryFnData`
- the [setQueryData](#queryclientsetquerydata) updater function or new data, will be called for each matching queryKey
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
## `queryClient.invalidateQueries`
The `invalidateQueries` method can be used to invalidate and refetch single or multiple queries in the cache based on their query keys or any other functionally accessible property/state of the query. By default, all matching queries are immediately marked as invalid and active queries are refetched in the background.
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
- If you **do not want active queries to refetch**, and simply be marked as invalid, you can use the `refetchType: 'none'` option.
- If you **want inactive queries to refetch** as well, use the `refetchType: 'all'` option
- For refetching, [queryClient.refetchQueries](#queryclientrefetchqueries) is called.
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
```tsx
await queryClient.invalidateQueries(
{
queryKey: ['posts'],
exact,
refetchType: 'active',
},
{ throwOnError, cancelRefetch },
)
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
```
**Options**
- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
- `queryKey?: QueryKey`: [Query Keys](../framework/react/guides/query-keys.md)
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
- `refetchType?: 'active' | 'inactive' | 'all' | 'none'`
- Defaults to `'active'`
- When set to `active`, only queries that match the refetch predicate and are actively being rendered via `useQuery` and friends will be refetched in the background.
- When set to `inactive`, only queries that match the refetch predicate and are NOT actively being rendered via `useQuery` and friends will be refetched in the background.
- When set to `all`, all queries that match the refetch predicate will be refetched in the background.
- When set to `none`, no queries will be refetched, and those that match the refetch predicate will be marked as invalid only.
- `options?: InvalidateOptions`:
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
- `throwOnError?: boolean`
- When set to `true`, this method will throw if any of the query refetch tasks fail.
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
- `cancelRefetch?: boolean`
- Defaults to `true`
- Per default, a currently running request will be cancelled before a new request is made
- When set to `false`, no refetch will be made if there is already a request running.
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
## `queryClient.refetchQueries`
The `refetchQueries` method can be used to refetch queries based on certain conditions.
Examples:
```tsx
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
// refetch all queries:
await queryClient.refetchQueries()
// refetch all stale queries:
await queryClient.refetchQueries({ stale: true })
// refetch all active queries partially matching a query key:
await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' })
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
// refetch all active queries exactly matching a query key:
await queryClient.refetchQueries({
queryKey: ['posts', 1],
type: 'active',
exact: true,
})
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
```
**Options**
- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
- `options?: RefetchOptions`:
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
- `throwOnError?: boolean`
- When set to `true`, this method will throw if any of the query refetch tasks fail.
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
- `cancelRefetch?: boolean`
- Defaults to `true`
- Per default, a currently running request will be cancelled before a new request is made
- When set to `false`, no refetch will be made if there is already a request running.
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
**Returns**
This function returns a promise that will resolve when all of the queries are done being refetched. By default, it **will not** throw an error if any of those queries refetches fail, but this can be configured by setting the `throwOnError` option to `true`
**Notes**
- Queries that are "disabled" because they only have disabled Observers will never be refetched.
- Queries that are "static" because they only have Observers with a Static StaleTime will never be refetched.
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
## `queryClient.cancelQueries`
The `cancelQueries` method can be used to cancel outgoing queries based on their query keys or any other functionally accessible property/state of the query.
This is most useful when performing optimistic updates since you will likely need to cancel any outgoing query refetches so they don't clobber your optimistic update when they resolve.
```tsx
await queryClient.cancelQueries(
{ queryKey: ['posts'], exact: true },
{ silent: true },
)
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
```
**Options**
- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
- `cancelOptions?: CancelOptions`: [Cancel Options](../framework/react/guides/query-cancellation.md#cancel-options)
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
**Returns**
This method does not return anything
## `queryClient.removeQueries`
The `removeQueries` method can be used to remove queries from the cache based on their query keys or any other functionally accessible property/state of the query.
```tsx
queryClient.removeQueries({ queryKey, exact: true })
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
```
**Options**
- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
**Returns**
This method does not return anything
## `queryClient.resetQueries`
The `resetQueries` method can be used to reset queries in the cache to their
initial state based on their query keys or any other functionally accessible
property/state of the query.
This will notify subscribers &mdash; unlike `clear`, which removes all
subscribers &mdash; and reset the query to its pre-loaded state &mdash; unlike
`invalidateQueries`. If a query has `initialData`, the query's data will be
reset to that. If a query is active, it will be refetched.
```tsx
queryClient.resetQueries({ queryKey, exact: true })
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
```
**Options**
- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
- `options?: ResetOptions`:
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
- `throwOnError?: boolean`
- When set to `true`, this method will throw if any of the query refetch tasks fail.
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
- `cancelRefetch?: boolean`
- Defaults to `true`
- Per default, a currently running request will be cancelled before a new request is made
- When set to `false`, no refetch will be made if there is already a request running.
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
**Returns**
This method returns a promise that resolves when all active queries have been refetched.
## `queryClient.isFetching`
This `isFetching` method returns an `integer` representing how many queries, if any, in the cache are currently fetching (including background-fetching, loading new pages, or loading more infinite query results)
```tsx
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
if (queryClient.isFetching()) {
console.log('At least one query is fetching!')
}
```
TanStack Query also exports a handy [`useIsFetching`](../framework/react/reference/useIsFetching.md) hook that will let you subscribe to this state in your components without creating a manual subscription to the query cache.
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
**Options**
- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
**Returns**
This method returns the number of fetching queries.
## `queryClient.isMutating`
This `isMutating` method returns an `integer` representing how many mutations, if any, in the cache are currently fetching.
```tsx
if (queryClient.isMutating()) {
console.log('At least one mutation is fetching!')
}
```
TanStack Query also exports a handy [`useIsMutating`](../framework/react/reference/useIsMutating.md) hook that will let you subscribe to this state in your components without creating a manual subscription to the mutation cache.
**Options**
- `filters: MutationFilters`: [Mutation Filters](../framework/react/guides/filters.md#mutation-filters)
**Returns**
This method returns the number of fetching mutations.
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
## `queryClient.getDefaultOptions`
The `getDefaultOptions` method returns the default options which have been set when creating the client or with `setDefaultOptions`.
```tsx
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
const defaultOptions = queryClient.getDefaultOptions()
```
## `queryClient.setDefaultOptions`
The `setDefaultOptions` method can be used to dynamically set the default options for this queryClient. Previously defined default options will be overwritten.
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
```tsx
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
queryClient.setDefaultOptions({
queries: {
staleTime: Infinity,
},
})
```
## `queryClient.getQueryDefaults`
The `getQueryDefaults` method returns the default options which have been set for specific queries:
```tsx
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
const defaultOptions = queryClient.getQueryDefaults(['posts'])
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
```
> Note that if several query defaults match the given query key, they will be merged together based on the order of registration.
> See [`setQueryDefaults`](#queryclientsetquerydefaults).
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
## `queryClient.setQueryDefaults`
`setQueryDefaults` can be used to set default options for specific queries:
```tsx
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts })
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
function Component() {
const { data } = useQuery({ queryKey: ['posts'] })
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
}
```
**Options**
- `queryKey: QueryKey`: [Query Keys](../framework/react/guides/query-keys.md)
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
- `options: QueryOptions`
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
> As stated in [`getQueryDefaults`](#queryclientgetquerydefaults), the order of registration of query defaults does matter.
> Since the matching defaults are merged by `getQueryDefaults`, the registration should be made in the following order: from the **most generic key** to the **least generic one** .
> This way, more specific defaults will override more generic defaults.
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
## `queryClient.getMutationDefaults`
The `getMutationDefaults` method returns the default options which have been set for specific mutations:
```tsx
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
const defaultOptions = queryClient.getMutationDefaults(['addPost'])
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
```
## `queryClient.setMutationDefaults`
`setMutationDefaults` can be used to set default options for specific mutations:
```tsx
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost })
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
function Component() {
const { data } = useMutation({ mutationKey: ['addPost'] })
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
}
```
**Options**
- `mutationKey: unknown[]`
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
- `options: MutationOptions`
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
> Similar to [`setQueryDefaults`](#queryclientsetquerydefaults), the order of registration does matter here.
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
## `queryClient.getQueryCache`
The `getQueryCache` method returns the query cache this client is connected to.
```tsx
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
const queryCache = queryClient.getQueryCache()
```
## `queryClient.getMutationCache`
The `getMutationCache` method returns the mutation cache this client is connected to.
```tsx
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
const mutationCache = queryClient.getMutationCache()
```
## `queryClient.clear`
The `clear` method clears all connected caches.
```tsx
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
queryClient.clear()
```
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
## `queryClient.resumePausedMutations`
Can be used to resume mutations that have been paused because there was no network connection.
```tsx
v4 release (#3842) * v4 alpha (#3060) * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * refactor(queryClient): remove undocumented methods * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * fix(queryFilters): fetchStatus to queryFilters (#3061) Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> BREAKING CHANGE: new query filters, query key must be an array * refactor(core): refactor internals from classes to a functions (#3066) * refactor(core): refactor retryer from a class to a function * refactor(core): refactor notifyManager from a class to a function * refactor(core): refactor notifyManager from a class to a function remove outdated comment * feat(useQueries): v4 api to take an object as input (#3071) * feat(useQueries): update API to use object syntax New v4 API - instead of taking an array of queries, `useQueries` now accepts an object with a `queries` key. The value of this key is an array of queries (this array is unchanged from v3). * test(useQueries): update tests for new API * docs(useQueries): update docs for v4 API * refactor(tests): adapt useInfiniteQuery test copied over from the react-18 branch, because that impl is less flaky * refactor(tests): adapt useInfiniteQuery test another one copied over from the react-18 branch, because that impl is less flaky * refactor: use a set for tracked props (#3085) * refactor: make listeners required because the only place where we pass no listener in is in tests * refactor: make notifyOnChangeProps a Set * chore: update tooling (#3086) * chore: update caniuselite * chore: remove const-enum babel plugin because we don't use const-enums anymore * chore: require ts 4.1 * chore: update rollup and plugins * chore: update typescript and ts-eslint * refactor: remove notifiable base class this abstraction costs more than the simple duplication, and we also have other notify functions which were not unified * fix(queryObserver): defer tracking of error prop when useErrorBoundary is on (#3087) adding "error" to the list of tracked properties will result in us _only_ tracking error if we want to track all properties implicitly by _not_ observing any properties (because we check for trackedProps.size). Moving the adding of "error" to _after_ the size check fixes this * docs: Update migrating-to-react-query-4.md (#3096) * refactor: remove logging in prod mode (#3103) to not log to the console per default; to access process.ENV, we need to enable node typings, which screws with setTimeout / setInterval, as typings are different for node and the browser; I tried to keep the changes to type-level only * refactor: remove cancel method as it no longer exists (#3142) * refactor: remove cancel method as it no longer exists it wasn't doing anything in that test * refactor: remove cancel method as it no longer exists use signal in playground example instead of cancel fn * refactor: remove unused query.setDefaultOptions * feat(persistQueryClient): improve persist controls (#3141) * feat(persistQueryClient): improve persist controls add restore/save/subscribe * docs: update persistQueryClient and hydration * docs: describe new persist features * docs(persistQueryClient): correct option defaults * feat(persistQueryClient): enable unsubscribe * docs(persistQueryClient): clarify restoration * docs(persistQueryClient): enable unsubscribe note * fix(persistQueryClient): subscribe awaits restore * docs: clarify caching behavior (#3221) The example contains at least one inacurate statement, > It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache. and could benefit from more precise language. * fix(core): do not refetch disabled queries (#3223) * fix(core): do not refetch disabled queries with refetchQueries or invalidateQueries + refetchType "inactive" disabled queries (=queries that have observers which are all enabled:false) are matched as "inactive"; this is okay when searching for them via findAll or for removeQueries, but the docs clearly state that refetchQueries / invalidateQueries do not refetch disabled queries, and that the only way to refetch them is via refetch returned from useQuery; this is important when using enabled to signal that some dependencies are not yet ready some tests needed to be adapted because we used disabled observer + refetchQueries a lot. The easiest way to emulate the observers we wanted here was mostly with initialData + staleTime, and to get a real inactive query, we just need to subscribe + unsubscribe immediately * fix(core): do not refetch disabled queries add tests for refetchQueries + disabled * fix(core): do not refetch disabled queries update test to make more sense - title said disabled queries, but we had no disabled query; test now does the opposite of what it did before, but that's what this PR does :) * refactor(mutation): remove mutation.cancel (#3225) as it wasn't really aborting the request - there is no AbortSignal for Mutations atm. * refactor(queryClient): add dev warning with queryDefaults (#3249) * refactor(QueryClient): add dev warning Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter. * test(QueryClient): warning with defaults options Highlight how query defaults registration order matters. * doc(QueryClient): add notes about query defaults In `getQueryDefaults`, the **first** matching default is returned. In `setQueryDefaults`, highlight how the registration order is important. * doc(QueryClient): fix link to documentation * test(QueryClient): better test * refactor(QueryClient): use internal logger * doc(QueryClient): fix markup * doc(QueryClient): remove extra entry * refacto(QueryClient): warn about several query defaults Warning must be displayed any time a conflict is detected, not just for dev build. The warning is aimed at helping developers *using* react-query, not those *developping* react-query. * Update src/core/queryClient.ts Remove useless optional chaining. Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(utils): add assert helper * refactor(QueryClient): add dev warning for mutation defaults * Revert "feat(utils): add assert helper" This reverts commit 05c3fe19cd3277bd99740564c2e771412b7cf109. * refactor(QueryClient): error when several defaults Review how the check for multiple defaults on a key is raised. Ensure it remains fast in release build. * refactor(QueryClient): inline code Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: fix silent merge conflicts * feat: Bail out if query data undefined (#3271) * Bail out if query data undefined * Fix failing test * docs: migration guide for undefined data * docs: update setQueryData reference * Update docs/src/pages/guides/migrating-to-react-query-4.md Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: add a test to ensure that callback on .mutate are only called for the last observer * docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 * refactor: inline / remove some functions for size improvements (#3289) * refactor: size inline reducers in query and mutation because they are only used from dispatch * refactor: remove default case in reducers actions are only produced by our own code, which is in TypeScript, so we'll get a type error if there is an action not handled. Unknown actions can't exist, as the tests show: we'd need a ts-expects-error to go this way * refactor: inline executeMutation because it's only used once * refactor: inline getObserver and updateObservers in useQueries because it's only used once * refactor: extract getDefaultState getDefaultState is a pure function, with no access to `this`, so we can extract it. This is in-line with what `mutation` is doing * refactor: remove getNextResult it was only used in tests, and it's also not documented * refactor: inline clearTimers because it's only used once * refactor: inline shouldNotifyListeners because it's only used once * refactor: inline resumePausedMutations * refactor: tests every stubbed queryFn needs a mock implementation to avoid console errors: Error: Query data cannot be undefined * refactor: do not log undefined query data warning to the console * feat: Version 4 codemods (#3195) * chore: add `jscodeshift` library to dev-dependencies We're planning to deliver codemods for the next release, so we will need this package to write codemods. * chore: add `@types/jscodeshift` library to dev-dependencies * chore: add an empty `jest` config file under the `codemods` directory For some reason the `moduleNameMapper` causes an error when running the codemod tests, it results in a `transformer is a not function` type error. In order to avoid this now, I add an empty config file and will investigate the root cause of the issue later. * chore: add a very basic codemod implementation and tests The current codemod is able to change the usages of `useQuery` according to the new API, so it will put the existing parameters into an object and pass it as the only parameter, but that's all. More changes coming soon. * chore: fix `prettier` errors in `use_query` codemod * chore: add missing `export` keywords to test suites in case of `use_query` codemod I just want to avoid `eslint` errors in the IDE. * feat(codemod): add basic codemods for query client methods * feat(codemod): add basic `useQueries` codemods * refactor(codemod): rework `useQuery` related codemods * feat(codemod): move files under `v4` directory We decided to move the version 4 related codemods under a separate directory. * chore(codemod): move `jscodeshift` library from `dependencies` to `devDependencies` Accidentally I added this package under `dependencies` but it should be placed under `devDependencies`. * chore(codemod): pick up codemods test by `npm test` From now the `npm test` command will execute the codemod tests as well. * refactor(codemod): remove `without-parameter` test case in case of `queryClient` related codemods This test case is not useful at all, it just adds extra code. * chore(codemod): remove duplications from `queryClient` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): rename `first-parameter-is-identifier` and `object-expression-parameter` test case * chore(codemod): rework `first-parameter-is-identifier` and `object-expression-parameter` test suites In these two test cases, we should try to collect as many test cases as possible. * chore(codemod): remove duplications from `useQuery` codemod testfixtures The number of duplications was just simply too much. It doesn't make any sense to maintain repetitive boilerplate code. * chore(codemod): add missing methods to the object syntax aware query client codemods The following methods were missing: - fetchInfiniteQuery - fetchQuery - prefetchInfiniteQuery - prefetchQuery * chore(codemod): add some more test cases to the `parameter-is-object` test suite * feat(codemod): add basic `useMutation` codemods * refactor(codemod): rename `queryKey` replacer and error, because now the key name can be parameterized * feat(codemod): add support for template literals * refactor(codemod): rename `object-syntax-aware` test to `query-client-methods` I want to combine two tests into a single one. * refactor(codemod): move testfixtures to the root level of `__testfixtures__` directory * refactor(codemod): combine the two `queryClient` codemods and test suites into a single one * refactor(codemod): move `useMutation` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_mutation` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * feat(codemod): add support for the following hook calls: - `useIsFetching` - `useIsMutating` * refactor(codemod): move `useQueries` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `use_queries` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): introduce `transformUseQueryLikeUsages` function Maybe this change will make the code read easier a bit. * refactor(codemod): do some refinements on the following tests: - `parameter-is-identifier` - `parameter-is-object-expression` * fix(codemod): in the case of JS, the string literal might be interpreted as `Literal` So without the additional `Literal` check, the codemod wouldn't be applied. * fix(codemod): remove `type` filter from import declarations This filter seems to be too strict because the codemods were not applied to the `examples` directory. * refactor(codemod): move `QueryClient` related parts and testfixutes to `useQuery` codemod The plan is to combine all existing codemods into a single one. * refactor(codemod): remove the whole `query_client_methods` library Regarding the necessary parts that were moved to the `useQuery` codemod, we don't need the leftover code anymore. * refactor(codemod): simplify entry point of the codemod It makes the code a bit slower, but on the other hand, it makes the code easier to read and understand. * feat(codemod): add basic `QueryCache` codemods * fix(codemod): do not transform array expression query keys We want arrays as query keys, so when the current query key is an array, we don't need to transform it. * fix(examples/playground): fix invalid usage of `invalidateQueries` * feat(codemod): show file path in console warnings * refactor(codemod): remove `use_query` directory We decided to group the codemods by major version numbers instead of types. The reason is simple: we will bundle all necessary transformations into a single file, so the consumers will have to apply only one codemod. Hopefully, it will make the DX better. * refactor(codemod): rename `use-query` to `key-transformation` The original `use-query` name is not valid anymore, because the codemod changes the signature of other function/method calls as well. * refactor(codemod): replace the transformer name in `key-transformation` codemod I renamed the transformer with the test, so the transformer name also needs to be updated in the test file. * chore(codemod): add codemod and utilities to the bundle We want the code mod to be part of the bundle. If it's part of the bundle, the consumers can directly access it through the `node_modules` directory and run it. We just simply would like to increase the DX. * refactor(codemod): rename function I shouldn't have committed this. :') * fix(codemod): keep `typeArguments` of the node It will prevent the removal of type annotations on a function/method call. * refactor(codemod): move `query-cache` test cases to `default-import` We want to cover the default, named, and namespaced imports in the case of `QueryCache` as well. * feat(codemod): add support for named imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of named imports as well. * fix(codemod): always return `Identifier` instance in case of `findImportIdentifier` of function Previously it returned a string as a default value and it could lead to errors in the code. * feat(codemod): add support for namespaced imports in case of `QueryCache` and `useQueryCache` The codemod must be able to transform usages in the case of namespaced imports as well. * refactor(codemod): re-use the previously written utility functions in the hook call transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): re-use the previously written utility functions in the query-client transformer By this, we can achieve the same functionality with less code repetition. * refactor(codemod): rename `hook-call-transformer` to `use-query-like` transformer I think this name describes better the purpose of this transformer. * chore(codemod): add todo about the `react-query` import check We shouldn't transform files that don't contain `react-query` imports. * refactor(codemod): make the `use-query-like-transformer` to look the same as other transformers I just want to follow the structure of other transformers. * fix(codemod): do not log warnings in the test environment Warning the user about the unprocessable query keys is useful in production, but in the test environment, it just makes it more difficult to read the output. * docs(codemod): add instructions how to apply codemods * chore(examples): apply codemod on the `examples` directory * docs(codemod): update `Codemod` section The suggested text sounds better. :) Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat: remove idle state (#3302) * feat: remove idle state in favor of status: loading & fetchStatus: idle * feat: remove idle state remove isIdle boolean * feat: remove idle state documentation around the removed idle state and the new fetchingStatus * feat: remove idle state add missing ' to docs * feat(*): add optional logger prop to QueryClient config (#3246) - remove setLogger - add optional `logger` prop to QueryClientConfig - add getLogger public method to QueryClient - add optional `logger` prop to QueryConfig and MutationConfig - add getDefaultLogger function which returns a default logger based on environment, which is used by everything that takes an optional logger in their config - add createQueryClient test util function that uses a mock logger - replace all `new QueryClient` calls with createQueryClient calls - remove mockConsoleError and usages from tests, which are not necessary anymore BREAKING CHANGE: remove setLogger * refactor: turn off error logging in tests the global `clearMocks: true` should make sure that this gets reset after every test * docs(examples): fix optimistic-updates-typescript example * chore(bundling): bundle for modern browsers (#3342) * chore(bundling): update babel dependencies * chore(bundling): remove babel-plugin-transform-async-to-promises we don't use async functions, and we also want to target envs that support async functions * chore(bundling): update supported browsers for a more modern output * chore(bundling): tweak browserslist and exclude transform-parameters plugin, which comes in because of any safari version, even though it should not be needed according to caniuse. This plugin transforms ES2015 parameters to ES5, this includes: Destructuring parameters, Default parameters and Rest parameters, all of which are supported by Safari * chore(bundling): update terser * chore(bundling): fix tests ReferenceError: Cannot access 'promiseResolve' before initialization * chore(bundling): docs about supported browsers * chore(bundling): small docs fixes * chore: eslint no-unnecessary-condition (#3344) * chore(eslint): turn on no-unnecessary-condition rule * chore(eslint): turn on no-unnecessary-condition rule remove unnecessary optional chainings in tests * chore(eslint): keep the matchMedia check even though it can never be undefined, except in tests, and I couldn't figure out how to mock that properly * chore(eslint): remove unnecessary checks in devtools * chore(eslint): addEventListener should exist on window if window is defined, which is checked by isServer * chore(eslint): assign default object to options instead of re-assigning it. In any case, the optional chaining is unnecessary * chore(eslint): action.type should always be defined * chore(eslint): keep the fallback for console * chore(eslint): one rule always complains so up-casting false to boolean * chore(eslint): if we have a behaviour, we also have na onFetch * chore(eslint): parseFilters always returns an object as it falls back to an empty object internally, so the falsy check didn't do anything * chore(eslint): upcast previous result to be potentially undefined to make the optinal chains necessary * fix issues after updating to alpha * fix(mutations): avoid infinite loading states if callbacks return an error (#3343) * fix(mutations): avoid infinite loading states if callbacks return an error add failing test cases * fix(mutations): avoid infinite loading states if callbacks return an error by making sure we always dispatch the error to go to error state internally; re-writing to async-await because it has better support than promise.finally, and the flow is also easier to reason about here * fix(mutations): fix merge conflicts * fix(react-native): bring back check for window.addEventListener (#3345) because it does not exist in RN, but window is defined * refactor(queryObserver): get rid of double-defaulting of options in getOptimisticResult every call to getOptimisticResult already contains defaulted options, which we can enforce on type level by only accepting DefaultedQueryObserverOptions * fix(createAsyncStoragePersister): persistClient respects throttleTime (#3331) (#3336) * docs: update persistQueryClient.md with Persister docs (#3356) * docs: add idb example * docs: consolidate sections storing ~> persistQueryClientSave restoring ~> persistQueryClientRestore * docs: create section for persisters * docs: focus cacheTime docs persistQueryClient and createWebStoragePersister are unrelated * docs: add tip for indexed db * docs: cleanup intro * docs: note additional interfaces available * docs: reorder api to be more intuitive * docs: improve wording * docs: add Offline React Query post (#3320) * docs: multi-line code snippet for layout on mobile * fix(mutations): allow passing a function to useErrorBoundary (#3390) * docs: idle state is removed * feat: Support the ability to provide a context (#2548) * Support providing a context * Addressing comments and merge conflicts from rebase * feat(persistQueryClient): PersistQueryClientProvider (#3248) * feat(persistQueryClient): PersistQueryClientProvider * feat(persistQueryClient): PersistQueryClientProvider defer subscription if we are hydrating * feat(persistQueryClient): PersistQueryClientProvider make sure we do not subscribe if the component unmounts before restoring has finished * feat(persistQueryClient): PersistQueryClientProvider make unsubscribe a const so that we don't mutate what we've exposed * feat(persistQueryClient): PersistQueryClientProvider make hydrating queries go in fetchStatus: 'idle' instead of paused because paused means we have started fetching and are pausing, and we will also continue, while with hydration, we haven't started fetching, and we also might not start if we get "fresh" data from hydration * feat(persistQueryClient): PersistQueryClientProvider don't export IsHydratingProvider, as it shouldn't be needed by consumers * feat(persistQueryClient): PersistQueryClientProvider provide onSuccess and onError callbacks to PersistQueryClientProvider so that you can react to the persisting having finished, to e.g. have a point where you can resumePausedMutations * feat(persistQueryClient): PersistQueryClientProvider tests for onSuccess callback, and remove onError callback, because the persister itself catches errors and removes the store * feat(persistQueryClient): PersistQueryClientProvider test for useQueries * feat(persistQueryClient): PersistQueryClientProvider docs * make restore in mockPersister a bit slower to stabilize tests * better persistQueryClient docs * feat(PersistQueryClientProvider): make sure we can hydrate into multiple clients and error handling * offline example * extract to custom hook * remove onError callback because errors are caught internally by persistQueryClient and the persisted client is then removed * just ignore stale hydrations if the client changes * Revert "just ignore stale hydrations if the client changes" This reverts commit 91e2afb7ba5b08dc86a188d7b9b21d07a8e3c440. * just ignore stale hydrations if the client changes this makes sure we only call onSuccess once, for the "latest" client * since QueryClientProviderProps is now a union type, we can't extend it from an interface * feat(cacheTime): default cacheTime to Infinity for SSR (#3377) * feat(cacheTime): default cacheTime to Infinity for SSR Cache persists for the lifecycle of request and can be immediately GCed afterward Helps close Node process immediately after use * docs: Add default server-side cacheTime to migration docs * docs(examples): fix offline example (#3463) * docs(examples): remove non-existing / unused imports * docs(examples): add missing msw dependency and fix some more things * fix(persistQueryClient): subscribe to both QueryCache and MutationCache * feat: add support for react 18 * feat(react): react-18 update react dependencies and add use-sync-external-store polyfill * feat(core): react-18 use a version of uSES that actually has an implementation other than "Not Yet Implemented" * feat(core): react-18 looks like we also need the experimental version of react, because v18-alpha doesn't support uSES yet. * feat(core): react-18 update testing-library to v13 alpha * feat(core): react-18 do not update currentResult when it is equal to the previousResult, because we use the currentResult as snapshot for uSES, so it must be as stable as possible * feat(core): react-18 switch forceUpdate with uSES. - I'm not sure if the `updateResult` effect is still necessary, or if it's guaranteed that we can't miss any updates because we don't subscribe in an effect anymore; tests behave the same with / without it - tbd - subscribe must be stable, or else we wind up in an infinite loop. in order to be able to pass `observer.subscribe`, we must bind the function in the constructor * feat(core): react-18 make the first test a bit more stable - we don't want more than 2 results * feat(core): react-18 fix type issues in devtools tests, so we adhere to the new typings of testing-library v13 * feat(core): react-18 make devtools test more resilient: act throws an error in the latest version if used liked that, but we don't need it. We can just click the button and use waitFor, as documented here: https://testing-library.com/docs/guide-disappearance#2-using-waitfor * feat(core): react-18 don't re-assign result * feat(core): react-18 bring back the optimistic result; this is debatable because it means we actually _ignore_ whe result returned by uSES, but it makes for fewer re-renders as we can go back to silently update from the effect * feat(core): react-18 useIsFetching to uSES I don't fully understand the test that needed adaption, but the new numbers actually look more correct. The first thing that happens is showing the SecondQuery (after 50ms), and at that time, the FirstQuery is already fetching, so why should there be two zeros in the result array ... judging from the console mock assertion, we are testing if state hasn't been updated on an unmounted component, which now can't happen anymore with uSES, so we can remove it * feat(core): react-18 useIsMutatating to uSES As a positive side-effect, there seem to be fewer re-renders now - the new numbers in the tests do make sense * feat(core): react-18 useMutation to uSES one big change is moving `setOptions` into a useEffect - similar to what `useQuery` is doing. However, we have no `getOptimisticResult` in useMutation, so we'll have to see how this behaves the tests need some love - it's generally working, but the way the tests are written, we're getting some failure. * feat(core): react-18 wait for heading to to to value `3` before asserting the onSuccess / onSettled calls * feat(core): react-18 rewrite test to getByRole * feat(core): react-18 since we're not returning anything from onError or onSettled in the tests, the mutation updates the data on the screen before the callbacks have finished running, which is why the test needs to waitFor the callbacks to have been called * feat(core): react-18 work around console error from uSES by moving the console mock to the client part and / or increasing the assertion count for now * feat(core): react-18 there seems to be one less rendering, likely because of batching, getting rid of one render that has the same assertions as the previous state, which is nice * feat(core): react-18 update shim * feat(core): react-18 update to v18 alpha, which should had the native uSES impl * feat(core): react-18 bump uSES * feat(core): react-18 count renders correctly by incrementing the count in useEffect * feat(core): react-18 bump everything and import from /shim * feat(core): react-18 make test more resilient by not using fireEvent * feat(core): react-18 use findByText for more resilient tests * feat(core): react-18 test against react 17 and react 18 * feat(core): react-18 only run bundlewatch once * feat(core): react-18 give a better name * feat(core): react-18 useQueries to uSES * feat(core): react-18 really upgrade react (with exact versions, because alphas) * feat(core): react-18 remove version logging * feat(core): react-18 remove fixed version in test:ci script * feat(core): react-18 try to get rid of warning in suspense test * feat(core): react-18 remove wrongful mock assertion - uSES should not console.error anymore * feat(core): react-18 add missing server-side snapshots * feat(core): react-18 fix build, error is: [!] Error: 'useSyncExternalStore' is not exported by node_modules/use-sync-external-store/shim/index.js, imported by src/react/useIsFetching.ts https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module * feat(hydration): remove hydration package (#2936) * V4: streamline cancel refetch (#2937) * feat: streamline cancelRefetch the following functions now default to true for cancelRefetch: - refetchQueries (+invalidateQueries, + resetQueries) - query.refetch - fetchNextPage (unchanged) - fetchPreviousPage (unchanged) * feat: streamline cancelRefetch make sure that refetchOnReconnect and refetchOnWindowFocus do not cancel already running requests * feat: streamline cancelRefetch update tests refetch and invalidate now both cancel previous queries, which is intended, so we get more calls to the queryFn in these cases * feat: streamline cancelRefetch add more tests for cancelRefetch behavior * feat: streamline cancelRefetch update docs and migration guide * feat: streamline cancelRefetch simplify conditions by moving the ?? true default down to fetch on observer level; all 3 callers (fetchNextPage, fetchPreviousPage and refetch) just pass their options down and adhere to this default; refetch also only has 3 callers: - refetch from useQuery, where we want the default - onOnline and onFocus, where we now explicitly pass false to keep the previous behavior and add more tests * feat: streamline cancelRefetch we always call this.fetch() with options, so we can just as well make the mandatory also, streamline signatures by destructing values that can't be forwarded (and use empty object as default value) in options and just spread the rest * feat: streamline cancelRefetch fix types for refetch it was accidentally made too wide and allowed all refetchFilters, like `predicate`; but with `refetch` on an obserserver, there is nothing to filter for, except the page, so that is what we need to accept via `RefetchPageFilters` * feat: streamline cancelRefetch refetch never took a queryKey as param - it is always bound to the observer * feat: better query filters (#2938) * feat(core): react-18 bump dependencies to beta * feat(core): react-18 fix assertions about special react markup * feat(core): react-18 try to make ssr hydration tests work, but skip them for now * feat(core): react-18 bring back batching. for this to work, we need to batch the actual calls to `onStoreChange` received from uSES, and scheduleMicroTask also needs to defer one tick with setTimeout (couldn't find a better way) * feat(core): react-18 reduce timeout to make test less flaky * feat(core): react-18 fix useIsMutating tests: The same value can't really appear twice in the array because re-renders are batched; this seems like a nice improvement due to uSES * feat(core): react-18 make tests slower; it seems that batching together with a sleep(0) actually batches fast responses together, so we now go directly from idle to success * fix: rename react directory to reactjs (#2884) * fix: rename react directory to reactjs the directory being named "react" causes an error with the moduleDirectories option from jest * fix: update package.json files to match the updated reactjs directory name * fix: change react test utils imports to match new directory name * docs(v4): add renamed reactjs details to migration guide Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> * feat: mutation cache duration (#2963) * feat: mutation cachetime stramline queryCache / mutationCache events by combining them into notifiable.ts * feat: mutation cachetime removable * feat: mutation cachetime add gc to mutations * feat: mutation cachetime streamline event types between queries and mutations * feat: mutation cachetime tests, and I forgot to implement optionalRemove, so make it abstract * feat: mutation cachetime replicate gc behavior from https://github.com/tannerlinsley/react-query/pull/2950 and add more tests * feat: mutation cachetime get test coverage back to 100% * feat: mutation cachetime docs * feat: mutation cachetime try to make tests more resilient * feat: mutation cachetime fix imports after merge conflict * feat(core): react-18 make ssr tests work in react 18: the updated fetch count is actually correct, as we always fetch once on the server, then sometimes another time on the client. see also this discussion: https://github.com/TkDodo/react-query/pull/2/files#r751305071 * feat(core): react-18 try to make tests work in 17 and 18 because of the different batching, we sometimes get different results, which we can avoid by making the tests really async and do some data fetching that takes at least some time, and write the tests more resilient * feat(core): react-18 resilient tests * refactor(persistQueryClient): Make persistQueryClient stable (#2961) * :truck: Remove experimental from persist-query-client * :truck: Rename persistor -> persister * ✏️ Fix Persistor -> Persister in imports * :truck: Update name in rollup config * :truck: Move createAsyncStoragePersister and createWebStoragePersister to stable version and rename persistor -> persister * 📝 Update documentation * 📝 Add migrating to v4 docs * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * feat(core): react-18 continue to stabilize tests * 2964 changes to on success callback (#2969) * feat(useQuery): onSuccess callback do not call onSuccess if update was done manually from setQueryData * feat(useQuery): onSuccess callback test that onSuccess is not called when setQueryData is used * feat(useQuery): onSuccess callback docs changes * feat(useQuery): onSuccess callback options spread is wrong - `updatedAt` is actually `dataUpdatedAt`. Oddly we didn't have a test, so I added one * 2919 query key array (#2988) * feat: query key array remove code that internally ensures that we get an Array, because it is now the expected interface, ensured by TypeScript * feat: query key array update tests to the new syntax * feat: query key array fix assertions, because there is no array wrapping happening internally anymore. The key you receive from the context is exactly the key you passed in * feat: query key array this test doesn't make much sense anymore * feat: query key array wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array * feat: query key array make docs adhere to new array key syntax * feat: query key array migration docs * feat(QueryObserver): track queries as default (#2987) * feat(Query Options): remove notifyOnChangePropsExclusion - remove related code from queryObserver - remove type def - remove related tests * docs(Query Options): update notifyOnChangePropsExclusion sections - remove from api references - add to v4 migration guide * feat(QueryObserver): "tracked" as default behavior - remove "tracked" completely if notifyOnChangeProps is not defined, behave as v3 "tracked" - add `notifyOnChangeProps: 'all' to opt out of the smart tracking TODO: Now that default behavior has changed, work out the failed tests. Which parts to change for current ones and possibly write new ones. * test(useQuery): adjust tests to pass for notifyOnChangeProps udpate * test(useInfiniteQuery): adjust tests to pass for notifyOnChangeProps udpate * test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChangeProps udpate * refactor(QueryObserver): use nullish coalescing operator much cleaner than the negated if I started with * test(QueryResetErrorBoundary): remove "tracked" from test * revert: test(QueryResetErrorBoundary): adjust tests to pass for notifyOnChaneProps udpate This reverts commit a34b4720675dad5ee6ebde401639f328c0c83122. The changes are not necessary after PR #2993 fix. * refactor(QueryObserver): combine prop checks * docs(notifyOnChangeProps): update docs to reflect new api * refactor: Remove deprecated promise cancel (#2996) * :fire: Remove the cancel method on promise for cancelling promise * ✅ Fix query client tests * ✅ Update query and useQuery tests * ✅ Update use infinite query tests * 📝 Update migartion guide * :bug: Fix linking in documentation * :pencil: Fix grammatical errors in docs Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior * 🚨 Fix lint errors * :recycle: Move define signal property to a separate function Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * remove test that doesn't make sense anymore - we don't allow different falsy query keys now * feat(core): react-18 re-add missing import after merge conflicts * feat(core): react-18 we need to observe isFetching to get a re-render with it thanks to tracked queries being on per default now * feat(core): react-18 observe fields we are actually checking * feat(core): react-18 stabilize tests * feat(core): react-18 make one specific test assert differently for react17/18 because batching with uSES works slightly differently I think * feat(core): react-18 remove now unnecessary useEffect: uSES makes sure that we can't miss any query updates between creating the observer and subscribing to it, even if the shim is used * feat(core): react-18 stabilize useQueries test: since both queries have the same timeout, it seems that the initial updates are now batched, leading to 1 less re-render * feat(core): react-18 stabilize useQueries test: a little less rerenders * feat(core): react-18 stabilize useInfiniteQuery tests * feat(core): react-18 use setActTimeout in Blink to avoid warning in react17 * feat(core): react-18 nodejs types conflict :/ * feat(core): react-18 always schedule garbage collection instead of removing directly with cacheTime 0, as callbacks might not fire otherwise * ✅ Use getByLabelText for opening query details * :bug: Use findBy* instead of getBy* * feat(core): react-18 wait for button to appear before clicking it * feat(core): react-18 seems like a broke a cacheTime: 0 test with the latest changes that I can't fix even with making the test more stable, so I'm partially reverting that change. However, we really shouldn't call `remove` directly, but always `optionalRemove` to never remove fetching queries. * feat(core): react-18 okay, lets go back to always instantly removing if we have 0 cacheTime. Not sure why the optionalRemove breaks a test * feat(core): react-18 stabilize flaky test - some renders seem to be batched if we don't sleep enough * feat(core): react-18 adapt scheduleMicroTask: we don't need to defer error throwing anymore now that we always defer with sleep(0) initially, which means the test only needs to assure that the callback is not invoked immediately, but deferred by one Promise "tick" * feat(core): react-18 fix suspense tests: since scheduleMicroTask now always defers by a promise tick (setTimeout(0)), and callbacks are batched into this, it takes one tick longer until the callbacks are invoked; we can "fix" that with a sleep(0) in the tests, or just by using waitFor to wait until the callbacks have been called * ✅ Make sorting test more robust * ✅ Make queries dependent on each other * 2927 offline queries (#3006) * feat(useQuery): offline queries remove defaultQueryObserverOptions because it is the same as defaultQueryOptions and we can just use that * feat(useQuery): offline queries setup dependent default values, to make it easier to work with them * feat(useQuery): offline queries basic changes to retryer: - pause the query before fetching depending upon networkMode - pause retries depending upon networkRetry * feat(useQuery): offline queries move networkRetry and networkMode defaults to the retryer creation, because we need the same for mutations * feat(useQuery): offline queries decouple focus and online manager: we're now informing caches of a focus when we're focussed, and about an online event if we come online; if the retryer continues, it can then decide to not fetch depending on our networkMode * feat(useQuery): offline queries expose isPaused on the queryResult and make sure isFetching is false when we are paused * feat(useQuery): offline queries knowing if we can fetch depends on if we are paused or not, as other conditions should apply also, rename options (not sure if that will stick though) * feat(useQuery): offline queries adjust existing tests for isPaused being exposed * feat(useQuery): offline queries fix existing test by setting options to emulate the previous behaviour, otherwise, with `mockNavigatorOnline` being set to false right from the start, the mutation would never fire off * feat(useQuery): offline queries adapt onOnline, onFocus tests to new behavior: they are now decoupled, and onOnline is always called even when not focused and vice versa. The retryer should make sure to not continue fetching if necessary * feat(useQuery): offline queries first test for networkMode * feat(useQuery): offline queries isFetching and isPaused are now derived and stored together in a fetchingState enum (idle, fetching, paused) * feat(useQuery): offline queries better networkMode api: online, always, offlineFirst (basically always but with paused retries) * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries more tests for networkMode: online * feat(useQuery): offline queries tests for networkMode: always * feat(useQuery): offline queries fix tests that were influencing each other by using proper jest mocks for online and visibility state * add paused queries to the devtools.tsx * feat(useQuery): offline queries never stop pausing when continueFn is called. Initially, I only had this guard for when it's called from the outside, e.g. for onWindowFocus while still being offline, but we need this always because otherwise query cancellation can potentially continue a paused query * feat(useQuery): offline queries okay, pausing multiple times was a bad idea, continueFn() will be called eventually anyways * feat(useQuery): offline queries attempt at offline toggle button * feat(useQuery): offline queries different icons, padding, color * feat(useQuery): offline queries i messed up the icon order * feat(useQuery): offline queries guard against illegal state transitions: paused queries can unmount or get cancelled, in which case we shouldn't continue them, even if we dispatch the continue event * feat(useQuery): offline queries fix devtools tests, account for paused queries * Revert "feat(useQuery): offline queries" This reverts commit a647f64a051ca4c02a872e7871b4b2ce49aeda2c. * feat(useQuery): offline queries keep the do-not-start logic out of the run function, and thus out of promiseOrValue. if the promise has already been resolved in the meantime, e.g. because of a `cancel`, the run method will just do nothing, while the previous logic would've started to fetch * feat(useQuery): offline queries show inactive as higher priority than paused * feat(useQuery): offline queries make sure that optimistic results don't show an intermediate fetching state, but go opmistically to paused instead * feat(useQuery): offline queries real result needs to match optimistic result * feat(useQuery): offline queries stupid mistake * feat(useQuery): offline queries keep status color and status label in sync * feat(useQuery): offline queries make networkMode param mandatory for canFetch (and default to online internally) so that we can't screw that up again * feat(useQuery): offline queries make sure test "finishes" to avoid prints to the console if another test goes online again * feat(useQuery): offline queries move cancel function to the top, as it's no longer dependent on the promise since the `.cancel` function is gone; all we need is to abort the signal and reject the promise of the retryer * feat(useQuery): offline queries inline canContinue, because it's now only called if the query is in paused state anyways * feat(useQuery): offline queries avoid the impossible state by not calling config.onContinue for already resolved queries, as that would put them right into fetching state again, without actually fetching * feat(useQuery): offline queries let resolved querie continue, but don't put them in fetching state * feat(useQuery): offline queries fix merge conflict and invert condition because no-negated-condition * feat(useQuery): offline queries add test for abort signal consumed - different results expected for node < 15 where we don't have AbortController, thus can't consume the signal * feat(useQuery): offline queries online queries should not fetch if paused and we go online when cancelled and no refetchOnReconnect * feat(useQuery): offline queries gc test * feat(useQuery): offline queries offlineFirst test * feat(useQuery): offline queries mock useMediaQuery to get rid of unnecessary check in devtools - if window is defined, `matchMedia` is also defined * feat(useQuery): offline queries use a higher retryDelay to make test more stable, otherwise, it might start retrying before we "go offline" * feat(useQuery): offline queries improve devtools test: check if onClick props are being called * feat(useQuery): offline queries add devtools test for offline mock * feat(useQuery): offline queries offline mutations test * feat(useQuery): offline queries network mode docs (unfinished) * feat(useQuery): offline queries network mode docs * feat(useQuery): offline queries fix merge conflicts * feat(core): react-18 fix new devtools test * feat(core): react-18 stabilize flaky test * feat(core): react-18 stabilize flaky test * refactor(queryClient): remove undocumented methods * feat(core): react-18 stabilize test: make sure we wait until we have really removed the data before we go online * feat(core): react-18 stabilize test with a sleep ¯\_(ツ)_/¯ * feat(core): react-18 add a dedicated script to test against react v17 * feat(core): react-18 queries need more "distance" between them to not be batched together and so that we get the expected render results in v17 and v18. if queries return faster, results will be batched, resulting in fewer re-renders, which is also good * feat(core): react-18 remove test about "unmounted" warning because we now uSES * feat(core): react-18 wrap update from inside useEffect in act, and make sure the queryFn doesn't return undefined * feat(core): react-18 devtools to uSES; since we have no stable snapshot - Object.values is always a new array, and queryCache.getAll() only changes if we add or remove things - we use the ref to let the getSnapshot function create a new array every time we have received an update from the subscription to trigger a re-render * feat(core): react-18 make devtools work in 18, but that brings back the act warnings in 17 * feat(core): react-18 stabilize another test * feat(core): react-18 stabilize tests: make sure that we wait for the test to finish to get rid of the act warning in 17 * feat(core): react-18 disable 3 ssr-hydration tests in react17 env. they use the shim, which uses layout effect under the hood if window is available, which doesn't work when rendering on the server; I've tried a lot to "mock" the correct environment, but to no success; the test will still run fine under react18 env, so I think we're good here * feat(core): react-18 flaky test much * feat(core): react-18 fix flaky test: we actually expect a length of two here, because suspense takes care of the intermediate loading state * feat(core): react-18 slowdown test some more to decrease flakyness * feat(core): react-18 simplify keepPreviousData tests. we are asserting all intermediate data steps anyways, and we don't really care about the intermediate fetching steps. exact batching happens depending on speed of the test / shim being used or not etc. Sometimes, intermediate steps are batched together into one re-render, which is not a bad thing. We would have to make the tests really slow to be super predictable though * fix: offline mutations fixes (#3051) * feat: offline mutations move reducer into Mutation class to avoid passing state (and options) around * feat: offline mutations optimistically set paused state depending on if we can fetch or not to avoid an intermediate state where we are loading but not paused * examples: fix query keys in basic examples because we need those for preview builds * fix(useMutation): make sure cacheCallbacks are always called even if the useMutation component unmounts and we have a cacheTime of 0; the fix was cherry-picked from the react-18 branch, where we also introduced this behavior * feat(core): react-18 there seems to be one less re-render, consistently, with this test * Feature/cachetime zero (#3054) * refactor: cacheTime-zero remove special handling for cacheTime: 0 and schedule a normal garbage collection for those queries. They will be eligible for gc after a setTimeout(0), but then they will only be optionally removed. This makes sure that paused queries are NOT gc'ed * refactor: cacheTime-zero remove special test "about online queries with cacheTime:0 should not fetch if paused and then unmounted". paused queries will now be kept until they continue, just like with every other query, unless query cancellation or abort signal was involved * refactor: cacheTime-zero adapt "remounting" test: if the same query with cacheTime 0 unmounts and remounts in the same cycle, the query will now be picked up and will not go to loading state again. I think this is okay * refactor: cacheTime-zero re-add instant query removal after fetching, because fetching via `queryClient.fetchQuery` will not remove the query otherwise, because the normal gc-mechanism now checks for `hadObservers` due to a suspense issue :/ * refactor: cacheTime-zero weird edge case: the previous logic was instantly removing the query _while_ it was still fetching, which is something we likely don't want. The data will stay in the currentQuery of the observer if the observer unsubscribes but still exists, and a new subscription will pick it up, unless the query was explicitly cancelled or the abort signal was consumed. * refactor: cacheTime-zero we need to wait a tick because even cacheTime 0 now waits at least a setTimeout(0) to be eligible for gc * refactor: cacheTime-zero schedule a new garbage collection after each new fetch; this won't do anything when you still have observers, but it fixes an edge case where prefetching took longer than the cacheTime, in which case the query was again never removed test needed adaption because we don't instantly remove, but deferred by a tick * refactor: cacheTime-zero stabilize test * refactor: cacheTime-zero apply a different suspense "workaround": do not garbage collect when fetching optimistically (done only by suspense) - gc will kick in once an observer subscribes; this will make sure we can still gc other fetches that don't have an observer consistently, like prefetching when the fetch takes longer than the gc time (which was leaking with the old workaround) * refactor: cacheTime-zero remove leftover * refactor: cacheTime-zero since every fetch triggers a new gc cycle, we don't need to do this in a loop anymore also, reset isFetchingOptimistic after every fetch * add publishing capabilities for alpha branch * feat(core): react-18 fix merge conflict * feat(core): react-18 remove duplicate test (introduced in merge conflict) * feat(core): react-18 flaky test * feat(core): react-18 try to make flaky test more stable * :recycle: Refactor devtools subscriptions * :sparkles: Move query states subscriptions to separate component * :recycle: Move active query to a separate component * feat(core): react-18 update to react-18 rc * feat(core): react-18 get rid of unused ts-expect-error, as we now have access to process.env * feat(core): react-18 tests: switch from .click() to fireEvent.click to avoid act warnings * feat(core): react-18 tests: fix suspense act warning * feat(core): react-18 use fireEvent.click() for tests because of act warnings * fix merge conflicts * more merge conflicts * another merge conflict: idle state doesn't exist anymore * fix tests, we need to check for fetchStatus now * remove unnecessary optional chaining in tests * prettier * useIsMutating: fix assertions - no more duplicates in react18 * also, no duplicate renderings for PersistQueryClient anymore * make tests more resilient don't wait for a specific time and then get, just try to find the text at all (timing with react18 can be different) * another flaky one * re-write new custom context tests to be the same as other tests * re-write new custom context tests to be the same as other tests * remove calls to getServerSnapshot it's optional and we don't do anything meaningful as of now in it; will need to re-add it once we do react18 hydration * Revert "remove calls to getServerSnapshot" This reverts commit eabcd4667523fbe44497a5e56815c9aa9b894f6a. * update to latest alphas an rcs * use testing-library 12 for react-17 test suite because the latest alpha dropped support for react17 * update from release candidates to actual releases * make another test more stable Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Rene Dellefont <renedellefont@gmail.com> * chore: release beta docs * docs: fix suspense example (#3458) * docs: fix suspense example * docs: fix useTransition interface * docs: fix suspense example * docs: fix useTransition interface Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> * docs(examples): update examples to use react18 (#3466) * tests: really assert that filtering works by checking that we never had two isFetchings * docs(examples): update react-scripts based examples to react18 and rq v4-beta * docs(examples): use react-query v4 in all examples * docs(examples): remove old version of persistence and use the dedicated provider instead * docs: use createRoot in the docs * docs(examples): fix import of createWebStoragePersister * docs(examples): make offline example a bit better * docs(QueryClient): fix indentation * fix(types): use react 18 types (#3482) * fix(types): fix promise inference in useQueries (#3493) * fix(types): handle Promise inference in useQueries * fix(types): prettier * docs(v4): update context example in v4 migration guide * test: stabilize new test * test: stabilize some more tests * fix(persistQueryClient): rename isHydrating to isRestoring (#3512) * fix(devtools): devtools should not import relatively from react-query * fix(hydration): properly remove unused hydration entry point hydration moved to the core, and the build entry point was already removed for v4. this is just a proper cleanup. * fix(persistQueryClient): rename isHydrating to isRestoring as we currently have no plans to re-use this for useHydrate, it would be confusing to not get true for this value in those cases * fix(persistQueryClient): document useIsRestoring * fix: make QueryErrorResetBoundary value stable we want a constant value for the lifetime of the QueryErrorResetBoundary component; useMemo doesn't guarantee that. * chore: remove resolutions from package.json as discussed here: https://github.com/tannerlinsley/react-query/pull/2688#discussion_r851847721 * fix: log message we don't have a queryKey at this point if a string was used due to how the overloads try to spread things * Update docs/src/pages/plugins/persistQueryClient.md * docs: fix offline example * fix: ESM compliant bundling (#3521) * fix various bundling issues * add package.json to exports * remove @svgr/rollup * remove node v12 from CI * support devtools/development * do not alias react-query * add side effect * remove "module" * fix * fix exports * add "module" * update @babel/runtime * don't preserve modules * switch back to babel * add migration note * update babel * update rollup * downgrade @rollup/plugin-commonjs * fix: Use fully-specified path to import use-sync-external-store/shim (#3561) * fix: move usage of React Context out of core package (#3578) * refactor: move test utils out of reactjs so that we can import them in core * refactor: move react specific utils back to reactjs * refactor: adapt test imports * refactor: move two tests to the reactjs package because they render a component * chore: setup eslint import zones so that we can't import anything into `core` that lives in other packages, like reactjs * fix: move usage of React Context out of core package by keeping HydrateOptions separate from React, and only add ContextOptions where necessary * fix: type issue when void or undefined is returned from query function (#3541) * fix(types): fix handling of promise return type in QueryFunctionData * fix(QueryFunction): return type restrict void and avoid union type distribution * fix(QueryClient): make setQueryDefaults compatible with adjusted QueryFunction type * fix(useQueries): correct type inferrence in GetResults with new QueryFunction type * fix(tests): adjust all test cases which use any or never as query function return type to comply with new QueryFunction type * fix(tests): change incorrect query function return types of query tests from string to unknown * feature(useQuery): add test cases covering void and Promise<void> return types * feature(useQueries): reject void or undefined as query function return type * feature(useQueries): add test cases for invalid query function return types * fix tsc error after rebasing lastest beta branch * fix: uSES import for react-native / esm (#3601) * fix(query): updating with setQueryData should not affect fetchStatus (#3613) queries can be fetching _while_ we are making a manual update are still fetching, so we have to set fields that affect the fetch conditionally (fetchStatus, fetchFailureCount) * chore: bump uSES to 1.1.0 (#3614) * fix(queryClient): make sure that setQueryData can return undefined from the updater function on type level (#3615) the only runtime tests we had didn't use the previous value, so the generic defaults to unknown; the TS error becomes apparent when providing a generic to setQueryData * docs: point offline example to /beta * feat(persistQueryClient): persist error handling (#3556) * refactor: remove type-fest as a dependency only used for the Promisable type, which is easy to recreate * feat(persistQueryClient): error handling strategies for persist plugins * feat(persistQueryClient): error handling strategies for persist plugins adapt tests * make handlePersistError return null to stop retries if null is returned, which is also the default strategy, the webstorage entry will be removed completely. * test for default behaviour * async version for persist error handling to make sync and async compatible, persist version must also throw an error to abort * make sure that async persister can accept sync error handlers * undefined errorStrategy, or return undefined from it, will just not persist anymore * rename to retry + documentation * improve docs * docs: update typescript.md * fix: make sure isDataEqual option is respected everywhere where we use structuralSharing (#3643) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it (#3507) * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it calling context.signal?.addEventListener did consume the signal * fix(infiniteQuery): do not consume AbortSignal unless user has consumed it fix formatting * re-write test to reflect the reality we want to continue fetching pages in the background even if the infinite query unmounts, unless the abort signal has been consumed. That is the documented behaviour, and also what useQuery is doing. * fix test * fix: useSyncExternalStore re-export (#3656) * fix: useSyncExternalStore re-export This is due to esm/cjs interop * fix: useSyncExternalStore re-export also fix react native re-export * test: try to stabilize tests * test: try to stabilize tests * fix(types): make sure queryClient.setQueriesData can return undefined from the updater (#3657) * fix(persist): remove environment check (#3658) because we can now pass in undefined for persisters during SSR, and the persisters themselves are not window related anymore, as we don't use window.localStorage directly * fix(types): remove non-void constraint from queryFn result (#3666) * fix(types): remove non-void constraint from queryFn result * test(types): remove non-void tests, and add tests for handling fetch -> promise<any> * test(types): remove ts-expect-error from query test file * feat: make InfiniteQueryObserver's type more robust (#3571) Co-authored-by: 廖璇 <arthur.liao@huolala.cn> * fix: `replaceDeepEqual` special case for non-plain arrays (#3669) * Fix case where replaceDeepEqual was returning incorrect value for non-plain arrays * fix pr comments * docs: restructure migration guide by importance of breaking changes * fix(persist): introduce in-house synchronous Storage interface (#3673) * docs: migrate to tanstack.com * examples: vendor to platform directories * Update index.js * Update config.json * update readme * Update README.md * docs: fix link typo in README.md (#3679) fix: link typo in README.md * docs: Update graphql.md to fix link (#3683) * tests: stabilize we don't care about intermediate results, and they might be render-batched * docs: rewrite typescript docs * docs: adapter teasers * Update config.json * Fix Best of JS badge in README (#3695) * docs: fix the broken links in network-mode.md (#3765) * Update network-mode.md Fix the url for query cancellation * Fix the remaining broken urls in network-mode.md * docs: fix the typo in persistQueryClient.md (#3768) Update subtitle `PeristQueryClientProvider` to `PersistQueryClientProvider`. * yarn -> npm * Monorepo, Rebrand to TanStack (#3708) * rebrand * move to src * chore: fix build by re-exporting types explicitly * chore: run everything through prettier * chore: bring back linting and compilation tasks * chore: setup eslint-import-resolver-typescript it still errors with import/no-unresolved, but I think that's because TS errors as well! * chore: fix a ton of imports * chore: down to zero ts errors * chore: export types separately to make the build work * chore: down to zero eslint issues 🎉 * chore: try to get tests to work * chore: make tests work * fix: use better match sorter primitives * chore: update workflows * Update ci.yml * chore: remove match-sorter dependency * chore: enable bundle size collection * chore: update to latest react * fix(devtools): fix typings of rankItems not sure if that is correct now... * chore: fix compilation * tests: fix tests by removing weird comment that is no longer necessary after upgrading react * tests: remove incrompehensible tests I don't know what these tests are doing, but overwriting useEffect is not something that makes sense now that we useSyncExternalStore for data fetching anyways ... * fix(devtools): fix sorting of queries rankItem doesn't take keys, so we have to pass the queryHash in directly to rank it * chore: setup ci pipeline and bundlewatch * chore: build during pr pipelines * chore: remove private:true as requested by CI: Error: Package undefined in /tmp/98d7e7a6 is set to private, remove package.json#private to publish it * Revert "chore: remove private:true" This reverts commit e1b237bf1a19901baf8b55c1d68a5627e27d7660. * chore: turn off import/no-unresolved in tests somehow, that fails in CI, and we have typescript protection against unresolved imports anyhow * fix: turn of import/no-unresolved for all tanstack imports * fix: regex * chore: do not run legacy pipelines on PRs * chore: fix ci check names * chore: add react-17 dependencies * chore: split up ci tasks * fix: building is done via bundlesize reporting so we don't need to build during testing * chore: try to make codesandbox ci work it requires package to be public, but for installing and yarn workspaces, we need it to be private * fix: apply private: false to all workspaces * fix: paths to sandboxes * chore: fix code coverage collection * chore: change imports from react-query to tanstack/react-query * docs: update migration docs with the rebrand * chore: revert codemod changes prettier destroyed the assertions * fix(useIsMutating): we need to subscribe to the right cache this is likely a copy-paste error, and the tests only worked because we render top-down; now, the tests make sure that components are re-rendered because of the subscription itself * Update README.md * docs: devtools documentation for tanstack rebrand * fix builds * chore: cleanup Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * chore: small beta fixes (#3800) * chore: fix the test:format and csb install scripts * chore: not sure why there is a lint error in this test... * chore: update lock files * chore: get basic example working again * Revert "chore: get basic example working again" This reverts commit a58472eb0f928edd6a6dc73c3c057e8226b2862a. * Revert "chore: update lock files" This reverts commit 8794f652e9e5059638a1b20f9a40d0f30cb18bf9. * refactor: webStoragPersister -> syncStoragePersister * feat(codemod): add codemod that replaces the react-query import specifiers (#3801) * feat(codemod): add codemod that replaces the react-query import specifiers * feat(codemod): add codemod that replaces the react-query import specifiers update migration docs * feat(codemod): add codemod that replaces the react-query import specifiers re-add yarn installation instructions * docs: Update installation.md (#3799) Update links to simple and basic examples * docs(mutations): fix typos (#3779) * docs: Update for typescript (#3789) Co-authored-by: simple <simple@woowahan.com> * docs: fix typo in ssr.md (#3748) whereever -> wherever * docs: Update useQueries hook example (#3710) I have used as an example "staleTime: Infinity", but it can be whatever makes sense here. I've had a hard time figuring out where to put my options just by reading the explanation below the code example. * chore: remove yarn.lock we use npm now * chore: fix the build 1) main field was wrong 2) useSyncExternalStore wasn't picked up correctly * fix: add react-dom as peer dependency (#3786) * rebase * react native * rebranded imports (#3803) * refactor: apply import codemod to examples * refactor: update import in typescript example * refactor: more import updates * chore: run prettier over examples * chore: try to setup codesandbox-ci for the monorepo structure * chore: force the use of npm ci in the pipeline * chore: install with leagacy peer deps * chore: try --force instead * chore: re-generate lock file in the hopes that it fixes the install problems * chore: force testing-library to v12.1.4 because 12.1.5 only supports react < 18, and we install both 17 and 18 * chore: try again with legacy peer deps now that only eslint-config is failing * chore: try if removing examples from workspaces changes a damn thing * Revert "chore: try if removing examples from workspaces changes a damn thing" This reverts commit c4be1847224e64599904779b6cdecd53de440d91. * chore: try a specific node version * chore: add dependencies to correct packages * chore: add missing dev dependencies (maybe) * chore: add more top level devDependencies * chore: move jscodeshift to the top, too * chore: try with npm install * chore: run node16 only! * chore: run node16 only * chore: remove devDependencies from top level package.json again root cause seems to be sub-packages not being installed with `npm ci`, so we switched to `npm install` instead * docs: Update installation.md (#3830) update bash install package from *@tanstack/react-query* to *react-query@beta* * feat(types): better type narrowing for useQuery when initialData is supplied (#3834) * Added a proof of concept for initialData * Fleshed out test * Completed overload change * More progress * Testing if a local tsconfig.json quiets down the errors * Fixed TS errors * fix(types): extract DefinedQueryResult and use that in tests * Apply suggestions from code review Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc> * docs(useQuery): add an explanation of isDataEqual option (#3838) * fix(devtools): make sure that sort function is properly read from localStorage (#3703) * fix(devtools): make sure that sort function is properly read from localStorage * test(devtools): wrap getByRole queries with explicit expect statements when the returned element is not used for assertions * chore(devtools): apply prettier formatting * chore: make broadcast-client experimental again (#3816) * chore: beta release (#3815) * chore: remove leftover yarn.lock files we use npm now * chore: pin node version to 16.14.2 * chore: run tests before releasing * chore: make test-and-publish script only run on TanStack/query Co-authored-by: Rene Dellefont <renedellefont@gmail.com> Co-authored-by: Anthony Fertil <anthony.fertil@hotmail.fr> Co-authored-by: Jonathan Stanley <jonathanstanley@users.noreply.github.com> Co-authored-by: Eduard Bardají Puig <ebardaji@gmail.com> Co-authored-by: GLabat <labat.guillaume@gmail.com> Co-authored-by: Guillaume Labat <guillaume.labat+git@imagino.com> Co-authored-by: phatmann <thephatmann@gmail.com> Co-authored-by: Louis Law <louiscklaw@users.noreply.github.com> Co-authored-by: hverlin <hugues.verlin@gmail.com> Co-authored-by: Balázs Máté Petró <petrobalazsmate@gmail.com> Co-authored-by: Anıl Anar <anilanar@users.noreply.github.com> Co-authored-by: Alvin Huang <huanguolin@outlook.com> Co-authored-by: Mostafa Nawara <nawaragfx@gmail.com> Co-authored-by: Nick Galloway <blackarctic@icloud.com> Co-authored-by: JacobLey <37151850+JacobLey@users.noreply.github.com> Co-authored-by: Eddy <eddyvinck95@gmail.com> Co-authored-by: Eddy Vinck <eddy.vinck@isaac.nl> Co-authored-by: Prateek Surana <prateeksurana3255@gmail.com> Co-authored-by: Nika Sepiskveradze <62851300+nikasepiskveradze@users.noreply.github.com> Co-authored-by: Nika Sepiskveradze <nsepiskveradze@exadel.com> Co-authored-by: Arty <26905074+artysidorenko@users.noreply.github.com> Co-authored-by: Sachin Raja <sachinraja2349@gmail.com> Co-authored-by: Hikari Hayashi <rev.hikari@gmail.com> Co-authored-by: Yannick Stachelscheid <yannickstach@googlemail.com> Co-authored-by: Hirbod <504909+hirbod@users.noreply.github.com> Co-authored-by: liaoliao666 <1076988944@qq.com> Co-authored-by: 廖璇 <arthur.liao@huolala.cn> Co-authored-by: moxey.eth <jakemoxey@gmail.com> Co-authored-by: Fedir Ushakov <pmahotsava@gmail.com> Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> Co-authored-by: Young <littlehaker@gmail.com> Co-authored-by: Sam Kvale <kvalesam@gmail.com> Co-authored-by: Michael Rambeau <mikeair@gmail.com> Co-authored-by: Brad Zickafoose <brad@viziworx.com> Co-authored-by: 庄宏基 <zhuanghongji.com@gmail.com> Co-authored-by: Tristan Marsh <tristan.marsh@canva.com> Co-authored-by: Morley Tatro <morleytatro@gmail.com> Co-authored-by: Kim JeongHyeok <42544600+zereight@users.noreply.github.com> Co-authored-by: simple <simple@woowahan.com> Co-authored-by: Ikko Ashimine <eltociear@gmail.com> Co-authored-by: webbalea <93341350+webbalea@users.noreply.github.com> Co-authored-by: Duarte Nunes <duarte@fastmail.com> Co-authored-by: Eko Setiyo Budi Purnomo <32205313+EkoSetiyo13@users.noreply.github.com> Co-authored-by: Matt Pocock <mattpocockvoice@gmail.com> Co-authored-by: airman5573 <68623798+airman5573@users.noreply.github.com> Co-authored-by: Michal Tecza <zorza2@gmail.com>
2022-07-18 20:08:12 +02:00
queryClient.resumePausedMutations()
```