Skip to content

Commit 315f0cf

Browse files
authored
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
1 parent fe98d53 commit 315f0cf

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+318
-584
lines changed

docs/src/manifests/manifest.json

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,11 @@
195195
"path": "/guides/suspense",
196196
"editUrl": "/guides/suspense.md"
197197
},
198+
{
199+
"title": "Custom Logger",
200+
"path": "/guides/custom-logger",
201+
"editUrl": "/guides/custom-logger.md"
202+
},
198203
{
199204
"title": "Testing",
200205
"path": "/guides/testing",
@@ -444,11 +449,6 @@
444449
"path": "/reference/onlineManager",
445450
"editUrl": "/reference/onlineManager.md"
446451
},
447-
{
448-
"title": "setLogger",
449-
"path": "/reference/setLogger",
450-
"editUrl": "/reference/setLogger.md"
451-
},
452452
{
453453
"title": "hydration",
454454
"path": "/reference/hydration",
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
id: custom-logger
3+
title: Custom Logger
4+
---
5+
6+
If you want to change how information is logged by React Query, you can set a custom logger when creating a `QueryClient`.
7+
8+
```js
9+
const queryClient = new QueryClient({
10+
logger: {
11+
log: (...args) => {
12+
// Log debugging information
13+
},
14+
warn: (...args) => {
15+
// Log warning
16+
},
17+
error: (...args) => {
18+
// Log error
19+
},
20+
},
21+
})
22+
```

docs/src/pages/guides/migrating-to-react-query-4.md

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,11 +260,24 @@ Additionally, `query.setDefaultOptions` was removed because it was also unused.
260260

261261
Types now require using TypeScript v4.1 or greater
262262

263-
### Logging
263+
### Logging in production
264264

265265
Starting with v4, react-query will no longer log errors (e.g. failed fetches) to the console in production mode, as this was confusing to many.
266266
Errors will still show up in development mode.
267267

268+
### `setLogger` is removed
269+
270+
It was possible to change the logger globally by calling `setLogger`. In v4, that function is replaced with an optional field when creating a `QueryClient`.
271+
272+
```diff
273+
- import { QueryClient, setLogger } from 'react-query';
274+
+ import { QueryClient } from 'react-query';
275+
276+
- setLogger(customLogger)
277+
- const queryClient = new QueryClient();
278+
+ const queryClient = new QueryClient({ logger: customLogger })
279+
```
280+
268281
### Undefined is an illegale cache value for successful queries
269282

270283
In order to make bailing out of updates possible by returning `undefined`, we had to make `undefined` an illegal cache value. This is in-line with other concepts of react-query, for example, returning `undefined` from the [initialData function](guides/initial-query-data#initial-data-function) will also _not_ set data.

docs/src/pages/guides/testing.md

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -71,17 +71,18 @@ This will set the defaults for all queries in the component tree to "no retries"
7171
## Turn off network error logging
7272

7373
When testing we want to suppress network errors being logged to the console.
74-
To do this, we can use `react-query`'s `setLogger()` function.
74+
To do this, we can pass a custom logger to `QueryClient`:
7575

7676
```ts
77-
// as part of your test setup
78-
import { setLogger } from 'react-query'
79-
80-
setLogger({
81-
log: console.log,
82-
warn: console.warn,
83-
// ✅ no more errors on the console
84-
error: () => {},
77+
import { QueryClient } from 'react-query'
78+
79+
const queryClient = new QueryClient({
80+
logger: {
81+
log: console.log,
82+
warn: console.warn,
83+
// ✅ no more errors on the console for tests
84+
error: process.env.NODE_ENV === 'test' ? () => {} : console.error,
85+
},
8586
})
8687
```
8788

@@ -181,6 +182,7 @@ expect(result.current.data.pages).toStrictEqual([
181182
182183
expectation.done();
183184
```
185+
184186
## Further reading
185187

186188
For additional tips and an alternative setup using `mock-service-worker`, have a look at [Testing React Query](../community/tkdodos-blog#5-testing-react-query) from

docs/src/pages/reference/QueryClient.md

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ Its available methods are:
3939
- [`queryClient.resetQueries`](#queryclientresetqueries)
4040
- [`queryClient.isFetching`](#queryclientisfetching)
4141
- [`queryClient.isMutating`](#queryclientismutating)
42+
- [`queryClient.getLogger`](#queryclientgetlogger)
4243
- [`queryClient.getDefaultOptions`](#queryclientgetdefaultoptions)
4344
- [`queryClient.setDefaultOptions`](#queryclientsetdefaultoptions)
4445
- [`queryClient.getQueryDefaults`](#queryclientgetquerydefaults)
@@ -57,6 +58,9 @@ Its available methods are:
5758
- `mutationCache?: MutationCache`
5859
- Optional
5960
- The mutation cache this client is connected to.
61+
- `logger?: Logger`
62+
- Optional
63+
- The logger this client uses to log debugging information, warnings and errors. If not set, `console` is the default logger.
6064
- `defaultOptions?: DefaultOptions`
6165
- Optional
6266
- Define defaults for all queries and mutations using this queryClient.
@@ -203,7 +207,7 @@ This distinction is more a "convenience" for ts devs that know which structure w
203207

204208
## `queryClient.setQueryData`
205209

206-
`setQueryData` is a synchronous function that can be used to immediately update a query's cached data. If the query does not exist, it will be created. **If the query is not utilized by a query hook in the default `cacheTime` of 5 minutes, the query will be garbage collected**. To update multiple queries at once and match query keys partially, you need to use [`queryClient.setQueriesData`](#queryclientsetqueriesdata) instead.
210+
`setQueryData` is a synchronous function that can be used to immediately update a query's cached data. If the query does not exist, it will be created. **If the query is not utilized by a query hook in the default `cacheTime` of 5 minutes, the query will be garbage collected**. To update multiple queries at once and match query keys partially, you need to use [`queryClient.setQueriesData`](#queryclientsetqueriesdata) instead.
207211

208212
> The difference between using `setQueryData` and `fetchQuery` is that `setQueryData` is sync and assumes that you already synchronously have the data available. If you need to fetch the data asynchronously, it's suggested that you either refetch the query key or use `fetchQuery` to handle the asynchronous fetch.
209213
@@ -450,6 +454,14 @@ React Query also exports a handy [`useIsMutating`](./useIsMutating) hook that wi
450454
**Returns**
451455

452456
This method returns the number of fetching mutations.
457+
## `queryClient.getLogger`
458+
459+
The `getLogger` method returns the logger which have been set when creating the client.
460+
461+
```js
462+
const logger = queryClient.getLogger()
463+
```
464+
453465
## `queryClient.getDefaultOptions`
454466

455467
The `getDefaultOptions` method returns the default options which have been set when creating the client or with `setDefaultOptions`.

docs/src/pages/reference/setLogger.md

Lines changed: 0 additions & 43 deletions
This file was deleted.

jest.config.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,5 @@ module.exports = {
77
moduleNameMapper: {
88
'react-query': '<rootDir>/src/index.ts',
99
},
10+
clearMocks: true,
1011
}

package.json

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,9 @@
1818
"es/index.js",
1919
"es/reactjs/index.js",
2020
"es/reactjs/setBatchUpdatesFn.js",
21-
"es/reactjs/setLogger.js",
2221
"lib/index.js",
2322
"lib/reactjs/index.js",
24-
"lib/reactjs/setBatchUpdatesFn.js",
25-
"lib/reactjs/setLogger.js"
23+
"lib/reactjs/setBatchUpdatesFn.js"
2624
],
2725
"scripts": {
2826
"test": "is-ci \"test:ci\" \"test:dev\"",

src/core/index.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ export { QueriesObserver } from './queriesObserver'
66
export { InfiniteQueryObserver } from './infiniteQueryObserver'
77
export { MutationCache } from './mutationCache'
88
export { MutationObserver } from './mutationObserver'
9-
export { setLogger } from './logger'
109
export { notifyManager } from './notifyManager'
1110
export { focusManager } from './focusManager'
1211
export { onlineManager } from './onlineManager'

src/core/logger.native.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import type { Logger } from './logger'
2+
3+
/**
4+
* See https://github.com/tannerlinsley/react-query/issues/795
5+
* and https://github.com/tannerlinsley/react-query/pull/3246/#discussion_r795105707
6+
*/
7+
export const defaultLogger: Logger = {
8+
log: console.log,
9+
warn: console.warn,
10+
error: console.warn,
11+
}

0 commit comments

Comments
 (0)