Skip to content

Commit

Permalink
feat: add support for react 18
Browse files Browse the repository at this point in the history
* 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 #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 a34b472.

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 a647f64.

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

* 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>
  • Loading branch information
5 people committed Apr 2, 2022
1 parent 39a213e commit 4d753c0
Show file tree
Hide file tree
Showing 31 changed files with 1,563 additions and 1,299 deletions.
7 changes: 5 additions & 2 deletions .github/workflows/test-and-publish.yml
Expand Up @@ -13,11 +13,12 @@ on:

jobs:
test:
name: 'Node ${{ matrix.node }}'
name: 'Node ${{ matrix.node }}, React ${{ matrix.react }}'
runs-on: ubuntu-latest
strategy:
matrix:
node: [12, 14, 16]
react: [17, 18]
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
Expand All @@ -26,8 +27,10 @@ jobs:
- name: Install dependencies
uses: bahmutov/npm-install@v1
- run: yarn test:ci
env:
REACTJS_VERSION: ${{ matrix.react }}
- run: yarn test:size
if: matrix.node == '16'
if: matrix.node == '16' && matrix.react == '18'
env:
BUNDLEWATCH_GITHUB_TOKEN: ${{ secrets.BUNDLEWATCH_GITHUB_TOKEN }}
- name: Upload coverage to Codecov
Expand Down
30 changes: 30 additions & 0 deletions jest.setup.js
Expand Up @@ -6,3 +6,33 @@ import { notifyManager } from './src'
notifyManager.setNotifyFunction(fn => {
act(fn)
})

jest.mock('react', () => {
const packages = {
18: 'react',
17: 'react-17',
}
const version = process.env.REACTJS_VERSION || '18'

return jest.requireActual(packages[version])
})

jest.mock('react-dom', () => {
const packages = {
18: 'react-dom',
17: 'react-dom-17',
}
const version = process.env.REACTJS_VERSION || '18'

return jest.requireActual(packages[version])
})

jest.mock('@testing-library/react', () => {
const packages = {
18: '@testing-library/react',
17: '@testing-library/react-17',
}
const version = process.env.REACTJS_VERSION || '18'

return jest.requireActual(packages[version])
})
21 changes: 14 additions & 7 deletions package.json
Expand Up @@ -25,6 +25,7 @@
"scripts": {
"test": "is-ci \"test:ci\" \"test:dev\"",
"test:dev": "npm run test:types && npm run test:format && npm run test:eslint && npm run test:codemod && jest --watch",
"test:dev:17": "npm run test:types && npm run test:format && npm run test:eslint && npm run test:codemod && REACTJS_VERSION=17 jest --watch",
"test:ci": "npm run test:types && npm run test:format && npm run test:eslint && npm run test:codemod && jest",
"test:coverage": "yarn test:ci; open coverage/lcov-report/index.html",
"test:format": "yarn prettier --check",
Expand Down Expand Up @@ -69,11 +70,13 @@
],
"dependencies": {
"@babel/runtime": "^7.5.5",
"@types/use-sync-external-store": "^0.0.3",
"broadcast-channel": "^3.4.1",
"match-sorter": "^6.0.2"
"match-sorter": "^6.0.2",
"use-sync-external-store": "^1.0.0"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0"
"react": "^16.8.0 || ^17.0.0 || ^18.0.0"
},
"peerDependenciesMeta": {
"react-dom": {
Expand All @@ -92,12 +95,14 @@
"@babel/preset-typescript": "^7.16.7",
"@rollup/plugin-replace": "^3.0.0",
"@svgr/rollup": "^6.1.1",
"@testing-library/react": "^13.0.0",
"@testing-library/react-17": "npm:@testing-library/react@^12.1.4",
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^10.4.7",
"@types/jest": "^26.0.4",
"@types/jscodeshift": "^0.11.3",
"@types/react": "^16.9.41",
"@types/react-dom": "^16.9.8",
"@types/node": "^16.11.10",
"@types/react": "^17.0.37",
"@types/react-dom": "^17.0.11",
"@typescript-eslint/eslint-plugin": "^5.6.0",
"@typescript-eslint/parser": "^5.6.0",
"babel-eslint": "^10.1.0",
Expand All @@ -122,8 +127,10 @@
"jest": "^26.0.1",
"jscodeshift": "^0.13.1",
"prettier": "2.2.1",
"react": "^16.13.0",
"react-dom": "^16.13.1",
"react": "^18.0.0",
"react-17": "npm:react@^17.0.2",
"react-dom": "^18.0.0",
"react-dom-17": "npm:react-dom@^17.0.2",
"react-error-boundary": "^2.2.2",
"replace": "^1.2.0",
"rimraf": "^3.0.2",
Expand Down
11 changes: 9 additions & 2 deletions rollup.config.js
Expand Up @@ -44,6 +44,13 @@ const inputSrcs = [
const extensions = ['.js', '.jsx', '.es6', '.es', '.mjs', '.ts', '.tsx']
const babelConfig = { extensions, runtimeHelpers: true }
const resolveConfig = { extensions }
const commonJsConfig = {
namedExports: {
'node_modules/use-sync-external-store/shim/index.js': [
'useSyncExternalStore',
],
},
}

export default inputSrcs
.map(([input, name, file]) => {
Expand All @@ -61,7 +68,7 @@ export default inputSrcs
plugins: [
resolve(resolveConfig),
babel(babelConfig),
commonJS(),
commonJS(commonJsConfig),
externalDeps(),
],
},
Expand All @@ -83,7 +90,7 @@ export default inputSrcs
}),
resolve(resolveConfig),
babel(babelConfig),
commonJS(),
commonJS(commonJsConfig),
externalDeps(),
terser(),
size(),
Expand Down
8 changes: 5 additions & 3 deletions src/core/queryObserver.ts
Expand Up @@ -570,15 +570,17 @@ export class QueryObserver<
| QueryObserverResult<TData, TError>
| undefined

this.currentResult = this.createResult(this.currentQuery, this.options)
const nextResult = this.createResult(this.currentQuery, this.options)
this.currentResultState = this.currentQuery.state
this.currentResultOptions = this.options

// Only notify if something has changed
if (shallowEqualObjects(this.currentResult, prevResult)) {
// Only notify and update result if something has changed
if (shallowEqualObjects(nextResult, prevResult)) {
return
}

this.currentResult = nextResult

// Determine which callbacks to trigger
const defaultNotifyOptions: NotifyOptions = { cache: true }

Expand Down
1 change: 1 addition & 0 deletions src/core/subscribable.ts
Expand Up @@ -5,6 +5,7 @@ export class Subscribable<TListener extends Function = Listener> {

constructor() {
this.listeners = []
this.subscribe = this.subscribe.bind(this)
}

subscribe(listener: TListener): () => void {
Expand Down
6 changes: 3 additions & 3 deletions src/core/tests/queryClient.test.tsx
@@ -1,4 +1,4 @@
import { waitFor } from '@testing-library/react'
import { fireEvent, waitFor } from '@testing-library/react'
import '@testing-library/jest-dom'
import React from 'react'

Expand Down Expand Up @@ -379,7 +379,7 @@ describe('queryClient', () => {
const rendered = renderWithClient(queryClient, <Page />)

await waitFor(() => rendered.getByText('data: data'))
rendered.getByRole('button', { name: /setQueryData/i }).click()
fireEvent.click(rendered.getByRole('button', { name: /setQueryData/i }))
await waitFor(() => rendered.getByText('data: newData'))

expect(onSuccess).toHaveBeenCalledTimes(1)
Expand Down Expand Up @@ -409,7 +409,7 @@ describe('queryClient', () => {
const rendered = renderWithClient(queryClient, <Page />)

await waitFor(() => rendered.getByText('data: data'))
rendered.getByRole('button', { name: /setQueryData/i }).click()
fireEvent.click(rendered.getByRole('button', { name: /setQueryData/i }))
await waitFor(() => rendered.getByText('data: newData'))
await waitFor(() => {
expect(rendered.getByText('dataUpdatedAt: 100')).toBeInTheDocument()
Expand Down
34 changes: 7 additions & 27 deletions src/core/tests/utils.test.tsx
Expand Up @@ -5,9 +5,9 @@ import {
parseMutationArgs,
matchMutation,
scheduleMicrotask,
sleep,
} from '../utils'
import { Mutation } from '../mutation'
import { waitFor } from '@testing-library/dom'
import { createQueryClient } from '../../reactjs/tests/utils'

describe('core/utils', () => {
Expand Down Expand Up @@ -330,33 +330,13 @@ describe('core/utils', () => {
})

describe('scheduleMicrotask', () => {
it('should throw an exception if the callback throw an error', async () => {
const error = new Error('error')
const callback = () => {
throw error
}
const errorSpy = jest.fn().mockImplementation(err => err)
jest.useFakeTimers()
const setTimeoutSpy = jest
.spyOn(globalThis, 'setTimeout')
.mockImplementation(function (handler: TimerHandler) {
try {
if (typeof handler === 'function') {
handler(errorSpy(error))
}
} catch (err: any) {
expect(err.message).toEqual('error')
// Do no throw an uncaught exception that cannot be tested with
// this jest version
}
return 0 as any
})
it('should defer execution of callback', async () => {
const callback = jest.fn()

scheduleMicrotask(callback)
jest.runAllTimers()
await waitFor(() => expect(setTimeoutSpy).toHaveBeenCalled())
expect(errorSpy).toHaveBeenCalled()
setTimeoutSpy.mockRestore()
jest.useRealTimers()
expect(callback).not.toHaveBeenCalled()
await sleep(0)
expect(callback).toHaveBeenCalledTimes(1)
})
})
})
10 changes: 2 additions & 8 deletions src/core/utils.ts
Expand Up @@ -404,14 +404,8 @@ export function sleep(timeout: number): Promise<void> {
* Schedules a microtask.
* This can be useful to schedule state updates after rendering.
*/
export function scheduleMicrotask(callback: () => void): void {
Promise.resolve()
.then(callback)
.catch(error =>
setTimeout(() => {
throw error
})
)
export function scheduleMicrotask(callback: () => void) {
sleep(0).then(callback)
}

export function getAbortController(): AbortController | undefined {
Expand Down

0 comments on commit 4d753c0

Please sign in to comment.