31 Commits

Author SHA1 Message Date
Wonsuk Choi
ed37a87ba9 chore(.gitignore): add 'next-env.d.ts' globally and remove tracked files (#10083) 2026-02-11 09:39:51 +01:00
Jonghyeon Ko
002550cb35 chore: add .vscode/mcp.json and .github/instructions/nx.instructions.md to .gitignore (#9325) 2025-06-29 00:37:51 +09:00
Jonghyeon Ko
51cc9e704e chore: add .cursor/rules to .gitignore (#9295) 2025-06-21 14:22:59 +09:00
Dominik Dorfmeister
97f55448b8 chore: composite monorepo (#8560)
* chore: query-query, react-query and persist-core to composite setup

* fix: self contain packages by having shared configs as symlinks

* fix: add tsConfigPaths to vite config

so that tests can pick up the path aliases

* chore: set outDir, rootDir and baseUrl for all packages

* chore: make legacy tsconfig extend regular tsconfig

* fix: tsc --build

* feat: setup project references

* fix: legacy configs also need references

* fix: oops

* fix: tsup related builds

we need to turn off composite builds for tsup

* fix: set rootDir for tsup builds

so that it can include all files it needs

* fix: remove dependencies on ^build

we no longer need builds to run tests / type checks

* fix: add separate out dir for tsc

* fix: include root eslint config in globals

* refactor: create compile task to depend on

* fix: typo

* fix: dynamic alisases for vitest

* chore: try to fix knip

* fix: make compile a cacheable task

* chore: temporary disable tests against older TS versions

* fix: ts doesn't like string return types

* fix(vue-query-devtools): fix build

* fix: test types

* Revert "chore: temporary disable tests against older TS versions"

This reverts commit 10ef560eb5.

* fix: make legacy ts builds output to their own directory

* chore: remove test:types from examples as they need a build step

* chore: fix knip

* chore: remove test:types from all examples

* Revert "Revert "chore: temporary disable tests against older TS versions""

This reverts commit d6daded7da.

* fix: outputs for compile task

* chore: remove test:types from integrations

* Revert "Revert "Revert "chore: temporary disable tests against older TS versions"""

This reverts commit 79b4844785.

---------

Co-authored-by: Damian Osipiuk <osipiukd+git@gmail.com>
2025-01-27 15:58:10 +01:00
Lachlan Collins
49795a3952 ci: Update Nx and @tanstack/config (#7580)
* ci: Update Nx and @tanstack/config

* Undo prettier change
2024-06-17 12:40:23 +10:00
Arnoud
1b59482cad feat(angular-query): rollup type declarations (#7380)
This has several benefits:

Fix internal resolution error
Clear API surface
IDEs will not suggest deep imports from unexpected files
2024-05-05 13:44:23 +02:00
Arnoud
ef1f7c1e37 feat(angular-query): injectMutationState (#6925)
* feat(angular-query): inject mutation state

* add type tests
2024-02-18 14:43:53 +01:00
Lachlan Collins
426bcd63b9 chore: Enable @typescript-eslint/stylistic config (#6914)
* Add @typescript-eslint/stylistic

* Remove knip ignore
2024-02-17 13:27:05 +11:00
Zachary DeRose
496cd8cdcc ci: More Nx Cloud features (#6906)
* adding root level checks to agent execution

* making root level scripts cacheable

* correctly setting inputs

* adding agents to ci.yml

* adding dynamic changesets to fix variable size PRs

* fixing resource name in dynamic-changesets.yaml

* reruning tests

* Delete tsbuildinfo file

* Update PR and CI scripts

* Add stop-agents-on-failure=false

* parallel=3

* Ignore .pnpm-store

---------

Co-authored-by: Lachlan Collins <1667261+lachlancollins@users.noreply.github.com>
2024-02-17 11:55:35 +11:00
Lachlan Collins
ae5527409b chore: Ignore .tsbuildinfo files (#6898) 2024-02-14 19:45:06 +11:00
Arnoud
3e852314e7 docs(angular-query): convert angular example apps to cli (#6849) 2024-02-07 23:03:14 +01:00
Lachlan Collins
422cbed783 ci: Use publish function from @tanstack/config (#6643)
* ci: Use publish function from @tanstack/config

* Remove type-fest
2024-01-05 12:01:37 +11:00
Lachlan Collins
ddf5539869 chore: Add type checking to integrations (#6607)
* Add TS to vue-vite integration

* Explicitly exclude examples

* Merge test:bundle into build

* Update gitignore

* Update codesandbox build step

* Wow npm is annoying
2023-12-29 08:29:31 +11:00
Lachlan Collins
1340d590a2 chore: Update to Nx v17 (#6581)
* chore: Update to Nx v17

* Fix pnpm lockfile
2023-12-23 23:24:16 +11:00
Lachlan Collins
83d71c3074 chore: Update to prettier v3.1.0 (#6378) 2023-11-15 14:15:47 +11:00
Lachlan Collins
129f8c9fad chore: Module resolution bundler (#6217) 2023-10-22 19:44:45 +11:00
Jonghyeon Ko
fe7df40289 chore(.eslintignore): add eslint ignoring rule (#5813)
* chore(.eslintignore): add ignoring rule

* chore(ignore): ignore build excluding top level

* chore: fix prettier

---------

Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc>
2023-08-01 15:04:34 +02:00
Zachary DeRose
2bab18520d chore: adding the nx-cloud task-runner (#5143)
* adding the nx-cloud task-runner

* empty commit to trigger ci with warm cache

* retrying after adding workspace to TanStack organization

* another empty commit...

* another empty commit...

* this is why I should never use the in-browser conflict resolver...

* another empty commit...

* another empty commit...

* Update packages/query-core/src/tests/hydration.test.tsx

Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc>

* rm console.log left in query core

* empty commit to trigger re-build

* updating nx cloud dependency

* empty commit to attempt to recreate unexpected cache miss

* gather hash data to check

* empty commit

* invalidating cache again

* removing old key and adding read-only key to source control

* empty commit

* updating build task

* adding rollup to cacheable operations

* fixing the project json file with better globs

* removing test:format and test:build as cacheable operations

* updating package scripts for better terminal logging

* removing comment left in

* bumping to latest cloud runner version

* updating pnpm-lock.yaml file

* adding skip-nx-cache to publish script

---------

Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc>
2023-04-01 08:55:31 +02:00
Julius Marminge
d9478e000c chore(ci): filter out examples (#4239)
* filter out examples

* typo

* update docs and gitignore to account for pnpm switch
2022-09-28 20:53:23 +02:00
Dominik Dorfmeister
357ec041a6 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)

* 🚚 Remove experimental from persist-query-client

* 🚚 Rename persistor -> persister

* ✏️  Fix Persistor -> Persister in imports

* 🚚 Update name in rollup config

* 🚚 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 a34b472067.

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)

* 🔥 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

* 🐛 Fix linking in documentation

* 📝 Fix grammatical errors in docs

Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc>

* :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior

* 🚨  Fix lint errors

* ♻️ 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 a647f64a05.

* 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 05c3fe19cd.

* 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 91e2afb7ba.

* 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)

* 🚚 Remove experimental from persist-query-client

* 🚚 Rename persistor -> persister

* ✏️  Fix Persistor -> Persister in imports

* 🚚 Update name in rollup config

* 🚚 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 a34b472067.

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)

* 🔥 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

* 🐛 Fix linking in documentation

* 📝 Fix grammatical errors in docs

Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc>

* :refactor: Use abortSignal for query cancellation in InfiniteQueryBehavior

* 🚨  Fix lint errors

* ♻️ 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

* 🐛 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 a647f64a05.

* 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

* ♻️ Refactor devtools subscriptions

*  Move query states subscriptions to separate component

* ♻️ 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 eabcd46675.

* 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 e1b237bf1a.

* 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 a58472eb0f.

* Revert "chore: update lock files"

This reverts commit 8794f652e9.

* 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 c4be184722.

* 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 12:08:12 -06:00
Lucas Genzelis
115895fc92 feat(useInfiniteQuery): respect cancelRefetch flag for infinite queries (fetchNextPage, fetchPreviousPage) (#2731) 2021-10-09 09:24:11 +02:00
Tanner Linsley
ac342e237a 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
Niek Bosch
3d967bf8ae feat: add support for tree shaking (#994) 2020-09-12 08:11:02 -07:00
Fredrik Höglund
d85f79bdf1 Add queryCache de/rehydration (#728)
* chore(hydration): set up separate hydration entry point

* feat(hydration): add support for de/rehydrating queryCaches

- Add dehydrate(queryCache, config)
- Add hydrate(queryCache, dehydratedQueries, config)
- Add useHydrate(dehydratedQueries, config)

* test(hydration): fix broken type in test

* rename scheduleTimeoutsManually to activateTimeoutsManually

* docs(hydration): add API-docs for hydration and update comparison

* docs(ssr): update ssr-docs with new approach based on de/rehydration

* remove activateTimeoutsManually

* add default shouldDehydrate

* add hydration/ReactQueryCacheProvider

* use unknown for initialData in dehydration

* rename initialQueries  and dehydratedQueries to dehydratedState

* include queryKey instead of queryHash in dehydration

* update initialQueries to dehydratedState in ssr guide docs

* remove shouldHydrate-option
2020-08-29 12:47:56 -06:00
Niek Bosch
73ccba8612 feat: publish new types (#897) 2020-08-20 10:46:20 -06:00
Niek Bosch
e23f9343fa refactor: add typescript support (#767) 2020-07-29 14:47:01 -06:00
Tanner Linsley
83ced96255 fix(suspense): Suspense instances now unmount properly 2020-05-11 08:04:02 -06:00
Tanner Linsley
89bec20393 Use deep equal to compare incoming data for referential stability
Fixes #430
2020-05-01 11:43:38 -06:00
Tanner Linsley
26c80ad74d Update queryCache 2020-03-13 13:40:21 -06:00
Tanner Linsley
1f3c641e53 Update gitignore and size plugin 2020-02-26 11:41:05 -07:00
tannerlinsley
08f61bd524 Initial commit 2019-09-10 13:22:26 -06:00