Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…nto fix/query-function-data-dont-accept-promise-undefined
  • Loading branch information
yss14 committed May 4, 2022
2 parents b9168c2 + fdbc002 commit 05e26ae
Show file tree
Hide file tree
Showing 60 changed files with 723 additions and 1,464 deletions.
6 changes: 4 additions & 2 deletions .babelrc.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const { NODE_ENV, BABEL_ENV } = process.env
const cjs = NODE_ENV === 'test' || BABEL_ENV === 'commonjs'
const es = BABEL_ENV === 'es'
const loose = true

module.exports = {
Expand All @@ -20,10 +21,11 @@ module.exports = {
],
plugins: [
cjs && ['@babel/transform-modules-commonjs', { loose }],
[
es && ['babel-plugin-add-import-extension', { extension: 'mjs' }],
// no runtime for umd builds
BABEL_ENV && [
'@babel/transform-runtime',
{
useESModules: !cjs,
version: require('./package.json').dependencies[
'@babel/runtime'
].replace(/^[^0-9]*/, ''),
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test-and-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
node: [12, 14, 16]
node: [14, 16]
react: [17, 18]
steps:
- uses: actions/checkout@v2
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ Enjoy this library? Try the entire [TanStack](https://tanstack.com)! [React Tabl

## Visit [react-query.tanstack.com](https://react-query.tanstack.com) for docs, guides, API and more!

Still on **React Query v2**? No problem! Check out the v2 docs here: https://react-query-v2.tanstack.com/.
Still on **React Query v2**? No problem! Check out the v2 docs here: https://react-query-v2.tanstack.com/. <br />
Would you like to try **React Query v4beta**? Check out the v4 beta docs here: https://react-query-beta.tanstack.com/.
## Quick Features

- Transport/protocol/backend agnostic data fetching (REST, GraphQL, promises, whatever!)
Expand Down
1 change: 1 addition & 0 deletions broadcastQueryClient-experimental/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from '../lib/broadcastQueryClient-experimental'
1 change: 1 addition & 0 deletions broadcastQueryClient-experimental/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('../lib/broadcastQueryClient-experimental/index')
1 change: 1 addition & 0 deletions core/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from '../lib/core'
1 change: 1 addition & 0 deletions core/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('../lib/core/index')
6 changes: 0 additions & 6 deletions core/package.json

This file was deleted.

1 change: 1 addition & 0 deletions createAsyncStoragePersister/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from '../lib/createAsyncStoragePersister'
1 change: 1 addition & 0 deletions createAsyncStoragePersister/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('../lib/createAsyncStoragePersister/index')
6 changes: 0 additions & 6 deletions createAsyncStoragePersister/package.json

This file was deleted.

1 change: 1 addition & 0 deletions createWebStoragePersister/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from '../lib/createWebStoragePersister'
1 change: 1 addition & 0 deletions createWebStoragePersister/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('../lib/createWebStoragePersister/index')
6 changes: 0 additions & 6 deletions createWebStoragePersister/package.json

This file was deleted.

1 change: 1 addition & 0 deletions devtools/development/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from '../../lib/devtools'
1 change: 1 addition & 0 deletions devtools/development/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('../../lib/devtools/index')
6 changes: 0 additions & 6 deletions devtools/development/package.json

This file was deleted.

1 change: 1 addition & 0 deletions devtools/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from '../lib/devtools'
11 changes: 2 additions & 9 deletions devtools/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
if (process.env.NODE_ENV !== 'development') {
module.exports = {
ReactQueryDevtools: function () {
return null
},
ReactQueryDevtoolsPanel: function () {
return null
},
}
module.exports = require('../lib/devtools/noop')
} else {
module.exports = require('./development')
module.exports = require('../lib/devtools/index')
}
6 changes: 0 additions & 6 deletions devtools/package.json

This file was deleted.

15 changes: 10 additions & 5 deletions docs/src/components/LayoutDocs.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export const LayoutDocs = props => {
<p className='text-sm'>
Fast track your learning and {' '}
<a
href="https://ui.dev/checkout/react-query?from=tanstack"
href="https://ui.dev/react-query?from=tanstack"
className="text-blue-600 font-semibold transition-colors duration-150 ease-out"
>
take the offical course ↗️
Expand All @@ -128,14 +128,19 @@ export const LayoutDocs = props => {
</div>
<div className="mt-12 relative">
<h4 className="font-semibold uppercase text-sm mb-2 mt-2 text-gray-500">
Subscribe to Bytes
Subscribe to{' '}
<a
className="text-blue-600"
href="https://bytes.dev?r=tanstack"
>
Bytes
</a>
</h4>
<p className="mt-4 text-sm leading-6 mb-4">
The best JavaScript newsletter! Delivered every
Monday to over 76,000 devs.
Your weekly dose of JavaScript news. Delivered every
Monday to over 80,000 devs, for free.
</p>
<BytesForm />

</div>
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion docs/src/components/Nav.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export const Nav = () => (
</div>
<div>
<a
href="https://learn.tanstack.com/p/react-query-essentials"
href="https://ui.dev/react-query?from=tanstack"
target="_blank"
className="leading-6 font-medium"
>
Expand Down
2 changes: 1 addition & 1 deletion docs/src/components/PPPBanner.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export function PPPBanner() {
Course with code{' '}
<a
className="underline cursor-pointer"
href={`/checkout/react-query?from=tanstack&coupon_code=${data.coupon}`}
href={`https://ui.dev/react-query?from=tanstack&coupon_code=${data.coupon}`}
>
<strong>{data.coupon}</strong>
</a>
Expand Down
48 changes: 26 additions & 22 deletions docs/src/pages/guides/migrating-to-react-query-4.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ title: Migrating to React Query 4

## Breaking Changes

### ESM Support

React Query now supports [package.json `"exports"`](https://nodejs.org/api/packages.html#exports) and is fully compatible with Node's native resolution for both CommonJS and ESM. We don't expect this to be a breaking change for most users, but this restricts the files you can import into your project to only the entry points we officially support.

### Query Keys (and Mutation Keys) need to be an Array

In v3, Query and Mutation Keys could be a String or an Array. Internally, React Query has always worked with Array Keys only, and we've sometimes exposed this to consumers. For example, in the `queryFn`, you would always get the key as an Array to make working with [Default Query Functions](./default-query-function) easier.
Expand Down Expand Up @@ -222,12 +226,12 @@ Even though React Query is an Async State Manager that can be used for anything
new QueryClient({
defaultOptions: {
queries: {
networkMode: 'offlineFirst'
networkMode: 'offlineFirst',
},
mutations: {
networkmode: 'offlineFirst'
}
}
networkmode: 'offlineFirst',
},
},
})
```

Expand All @@ -240,7 +244,6 @@ The `useQueries` hook now accepts an object with a `queries` prop as its input.
+ useQueries({ queries: [{ queryKey1, queryFn1, options1 }, { queryKey2, queryFn2, options2 }] })
```


### Removed undocumented methods from the `queryClient`, `query` and `mutation`

The methods `cancelMutatations` and `executeMutation` on the `QueryClient` were undocumented and unused internally, so we removed them. Since it was just a wrapper around a method available on the `mutationCache`, you can still use the functionality of `executeMutation`
Expand Down Expand Up @@ -289,10 +292,7 @@ In order to make bailing out of updates possible by returning `undefined`, we ha
Further, it is an easy bug to produce `Promise<void>` by adding logging in the queryFn:

```js
useQuery(
['key'],
() => axios.get(url).then(result => console.log(result.data))
)
useQuery(['key'], () => axios.get(url).then(result => console.log(result.data)))
```

This is now disallowed on type level; at runtime, `undefined` will be transformed to a _failed Promise_, which means you will get an `error`, which will also be logged to the console in development mode.
Expand Down Expand Up @@ -349,19 +349,18 @@ React Query defaults to "tracking" query properties, which should give you a nic
When using the [functional updater form of setQueryData](../reference/QueryClient#queryclientsetquerydata), you can now bail out of the update by returning `undefined`. This is helpful if `undefined` is given to you as `previousValue`, which means that currently, no cached entry exists and you don't want to / cannot create one, like in the example of toggling a todo:

```js
queryClient.setQueryData(
['todo', id],
(previousTodo) => previousTodo ? { ...previousTodo, done: true } : undefined
queryClient.setQueryData(['todo', id], previousTodo =>
previousTodo ? { ...previousTodo, done: true } : undefined
)
```
```

### Custom Contexts for Multiple Providers
### Custom Contexts for Multiple Providers

Custom contexts can now be specified to pair hooks with their matching `Provider`. This is critical when there may be multiple React Query `Provider` instances in the component tree, and you need to ensure your hook uses the correct `Provider` instance.

An example:

1) Create a data package.
1. Create a data package.

```tsx
// Our first data package: @my-scope/container-data
Expand All @@ -375,42 +374,47 @@ export const useUser = () => {
})
}

export const ContainerDataProvider = ({ children }: { children: React.ReactNode}) => {
export const ContainerDataProvider = ({
children,
}: {
children: React.ReactNode
}) => {
return (
<QueryClientProvider client={queryClient} context={context}>
{children}
</QueryClientProvider>
)
}

```

2) Create a second data package.
2. Create a second data package.

```tsx
// Our second data package: @my-scope/my-component-data

const context = React.createContext<QueryClient | undefined>(undefined)
const queryClient = new QueryClient()


export const useItems = () => {
return useQuery(ITEMS_KEY, ITEMS_FETCHER, {
context,
})
}

export const MyComponentDataProvider = ({ children }: { children: React.ReactNode}) => {
export const MyComponentDataProvider = ({
children,
}: {
children: React.ReactNode
}) => {
return (
<QueryClientProvider client={queryClient} context={context}>
{children}
</QueryClientProvider>
)
}

```

3) Use these two data packages in your application.
3. Use these two data packages in your application.

```tsx
// Our application
Expand Down
4 changes: 2 additions & 2 deletions docs/src/pages/guides/query-cancellation.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,8 @@ const query = useQuery(['todos'], ({ signal }) => {
You might want to cancel a query manually. For example, if the request takes a long time to finish, you can allow the user to click a cancel button to stop the request. To do this, you just need to call `queryClient.cancelQueries(key)`, which will cancel the query and revert it back to its previous state. If `promise.cancel` is available, or you have consumed the `signal` passed to the query function, React Query will additionally also cancel the Promise.
```js
const query = useQuery(['todos'], await ({ signal }) => {
const resp = fetch('/todos', { signal })
const query = useQuery(['todos'], async ({ signal }) => {
const resp = await fetch('/todos', { signal })
return resp.json()
})

Expand Down
8 changes: 4 additions & 4 deletions docs/src/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,10 @@ const Home = ({ sponsors }) => {
<p>
Want to skip the docs?{' '}
<a
href="https://ui.dev/checkout/react-query?from=tanstack"
href="https://ui.dev/react-query?from=tanstack"
className="text-blue-600 font-semibold transition-colors duration-150 ease-out"
>
Take the offical course
Take the official course
</a>
</p>
</div>
Expand Down Expand Up @@ -177,7 +177,7 @@ const Home = ({ sponsors }) => {
</span>
</div>
<a
href="https://ui.dev/checkout/react-query?from=tanstack"
href="https://ui.dev/react-query?from=tanstack"
target="_blank"
className="inline-block mt-8 rounded shadow-lg bg-coral text-white font-bold text-xl px-4 py-3"
>
Expand Down Expand Up @@ -375,7 +375,7 @@ const Home = ({ sponsors }) => {
</h2>
<div className="mt-8 flex lg:flex-shrink-0 md:mt-0">
<div className="inline-flex rounded-md shadow">
<a href="https://ui.dev/checkout/react-query?from=tanstack" className="inline-flex items-center justify-center text-center px-5 py-3 border border-transparent text-base leading-6 font-medium rounded-md text-white bg-coral hover:bg-coral-light focus:outline-none focus:shadow-outline transition duration-150 ease-in-out">
<a href="https://ui.dev/react-query?from=tanstack" className="inline-flex items-center justify-center text-center px-5 py-3 border border-transparent text-base leading-6 font-medium rounded-md text-white bg-coral hover:bg-coral-light focus:outline-none focus:shadow-outline transition duration-150 ease-in-out">
Take the course
</a>
</div>
Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,5 +84,5 @@ function Example() {

## You talked me into it, so what now?

- Consider taking the official [React Query Course](https://ui.dev/checkout/react-query?from=tanstack) (or buying it for your whole team!)
- Consider taking the official [React Query Course](https://ui.dev/react-query?from=tanstack) (or buying it for your whole team!)
- Learn React Query at your own pace with our amazingly thorough [Walkthrough Guide](../installation) and [API Reference](../reference/useQuery)
4 changes: 4 additions & 0 deletions docs/src/pages/plugins/persistQueryClient.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,10 @@ ReactDOM.createRoot(rootElement).render(
- will be called when the initial restore is finished
- can be used to [resumePausedMutations](../reference/QueryClient#queryclientresumepausedmutations)

### useIsRestoring

If you are using the `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid race conditions between the restore and mounting queries.

## Persisters

### Persisters Interface
Expand Down
13 changes: 8 additions & 5 deletions docs/src/pages/react-native.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,16 +55,19 @@ import React from 'react'
import { useFocusEffect } from '@react-navigation/native'

export function useRefreshOnFocus<T>(refetch: () => Promise<T>) {
const enabledRef = React.useRef(false)
const firstTimeRef = React.useRef(true)

useFocusEffect(
React.useCallback(() => {
if (enabledRef.current) {
refetch()
} else {
enabledRef.current = true
if (firstTimeRef.current) {
firstTimeRef.current = false;
return;
}

refetch()
}, [refetch])
)
}
```

In the above code, `refetch` is skipped the first time because `useFocusEffect` calls our callback on mount in addition to screen focus.
Loading

0 comments on commit 05e26ae

Please sign in to comment.