Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
tannerlinsley committed May 15, 2020
2 parents de633a3 + 51375fd commit 3ef9c7c
Show file tree
Hide file tree
Showing 20 changed files with 592 additions and 106 deletions.
12 changes: 10 additions & 2 deletions .babelrc
Expand Up @@ -10,7 +10,14 @@
],
"@babel/react"
],
"plugins": ["babel-plugin-transform-async-to-promises"],
"plugins": [
[
"babel-plugin-transform-async-to-promises",
{
externalHelpers: true
}
]
],
"env": {
"test": {
"presets": [
Expand All @@ -22,7 +29,8 @@
"exclude": ["@babel/plugin-transform-regenerator"]
}
]
]
],
"plugins": ["babel-plugin-transform-async-to-promises"]
}
}
}
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Expand Up @@ -24,7 +24,7 @@ If you have been assigned to fix an issue or develop a new feature, please follo
- To run examples, follow their individual directions. Usually this is just `$ yarn && yarn start`.
- To run examples using your local build, link to the local `react-query` by running `$ yarn link react-query` from the example's directory
- Document your changes in the appropriate doc page
- Git stage your required chnages and commit (see below commit guidelines)
- Git stage your required changes and commit (see below commit guidelines)
- Submit PR for review

## Commit message conventions
Expand Down
45 changes: 42 additions & 3 deletions README.md
Expand Up @@ -250,14 +250,17 @@ This library is being built and maintained by me, @tannerlinsley and I am always
- [`queryCache.getQueryData`](#querycachegetquerydata)
- [`queryCache.setQueryData`](#querycachesetquerydata)
- [`queryCache.refetchQueries`](#querycacherefetchqueries)
- [`queryCache.cancelQueries`](#querycachecancelqueries)
- [`queryCache.removeQueries`](#querycacheremovequeries)
- [`queryCache.getQuery`](#querycachegetquery)
- [`queryCache.getQueries`](#querycachegetqueries)
- [`queryCache.isFetching`](#querycacheisfetching)
- [`queryCache.subscribe`](#querycachesubscribe)
- [`queryCache.clear`](#querycacheclear)
- [`useQueryCache`](#usequerycache)
- [`useIsFetching`](#useisfetching)
- [`ReactQueryConfigProvider`](#reactqueryconfigprovider)
- [`ReactQueryCacheProvider`](#reactquerycacheprovider)
- [`setConsole`](#setconsole)
- [Contributors ✨](#contributors-)

Expand Down Expand Up @@ -2236,6 +2239,7 @@ The `queryCache` instance is the backbone of React Query that manages all of the
- [`getQueryData`](#querycachegetquerydata)
- [`setQueryData`](#querycachesetquerydata)
- [`refetchQueries`](#querycacherefetchqueries)
- [`cancelQueries`](#querycachecancelqueries)
- [`removeQueries`](#querycacheremovequeries)
- [`getQueries`](#querycachegetqueries)
- [`getQuery`](#querycachegetquery)
Expand Down Expand Up @@ -2361,7 +2365,7 @@ const queries = queryCache.refetchQueries(inclusiveQueryKeyOrPredicateFn, {
- This predicate function will be called for every single query in the cache and be expected to return truthy for queries that are `found`.
- The `exact` option has no effect with using a function
- `exact: Boolean`
- If you don't want to search queries inclusively by query key, you can pass the `exact: true` option to return only the query with the exact query key you have passed. Don't remember to destructure it out of the array!
- If you don't want to search queries inclusively by query key, you can pass the `exact: true` option to return only the query with the exact query key you have passed. Remember to destructure it out of the array!
- `throwOnError: Boolean`
- When set to `true`, this function will throw if any of the query refetch tasks fail.
- `force: Boolean`
Expand Down Expand Up @@ -2394,7 +2398,7 @@ const queries = queryCache.cancelQueries(queryKeyOrPredicateFn, {
- This predicate function will be called for every single query in the cache and be expected to return truthy for queries that are `found`.
- The `exact` option has no effect with using a function
- `exact: Boolean`
- If you don't want to search queries inclusively by query key, you can pass the `exact: true` option to return only the query with the exact query key you have passed. Don't remember to destructure it out of the array!
- If you don't want to search queries inclusively by query key, you can pass the `exact: true` option to return only the query with the exact query key you have passed. Remember to destructure it out of the array!

### Returns

Expand All @@ -2421,7 +2425,7 @@ const queries = queryCache.removeQueries(queryKeyOrPredicateFn, {
- This predicate function will be called for every single query in the cache and be expected to return truthy for queries that are `found`.
- The `exact` option has no effect with using a function
- `exact: Boolean`
- If you don't want to search queries inclusively by query key, you can pass the `exact: true` option to return only the query with the exact query key you have passed. Don't remember to destructure it out of the array!
- If you don't want to search queries inclusively by query key, you can pass the `exact: true` option to return only the query with the exact query key you have passed. Remember to destructure it out of the array!

### Returns

Expand Down Expand Up @@ -2522,6 +2526,18 @@ queryCache.clear()
- `queries: Array<Query>`
- This will be an array containing the queries that were found.
## `useQueryCache`
The `useQueryCache` hook returns the current queryCache instance.
```js
import { useQueryCache } from 'react-query';

const queryCache = useQueryCache()
```
If you are using the `ReactQueryCacheProvider` to set a custom cache, you cannot simply import `{ queryCache }` any more. This hook will ensure you're getting the correct instance.
## `useIsFetching`
`useIsFetching` is an optional hook that returns the `number` of the queries that your application is loading or fetching in the background (useful for app-wide loading indicators).
Expand Down Expand Up @@ -2582,6 +2598,29 @@ function App() {
- Must be **stable** or **memoized**. Do not create an inline object!
- For non-global properties please see their usage in both the [`useQuery` hook](#usequery) and the [`useMutation` hook](#usemutation).
## `ReactQueryCacheProvider`
`ReactQueryCacheProvider` is an optional provider component for explicitly setting the query cache used by React Query. This is useful for creating component-level caches that are not completely global, as well as making truly isolated unit tests.
```js
import { ReactQueryCacheProvider, makeQueryCache } from 'react-query';

const queryCache = makeQueryCache()

function App() {
return (
<ReactQueryCacheProvider queryCache={queryCache}>
...
</ReactQueryCacheProvider>
)
}
```
### Options
- `queryCache: Object`
- In instance of queryCache, you can use the `makeQueryCache` factory to create this.
- If not provided, a new cache will be generated.
## `setConsole`
`setConsole` is an optional utility function that allows you to replace the `console` interface used to log errors. By default, the `window.console` object is used. If no global `console` object is found in the environment, nothing will be logged.
Expand Down
2 changes: 1 addition & 1 deletion rollup.config.js
Expand Up @@ -32,7 +32,7 @@ export default [
sourcemap: true,
},
external,
plugins: [resolve(), babel(), commonJS(), externalDeps()],
plugins: [resolve(), babel(), commonJS(), externalDeps(), terser()],
},
{
input: 'src/index.js',
Expand Down
7 changes: 6 additions & 1 deletion src/index.js
@@ -1,4 +1,9 @@
export { queryCache } from './queryCache'
export {
queryCache,
makeQueryCache,
ReactQueryCacheProvider,
useQueryCache,
} from './queryCache'
export { ReactQueryConfigProvider } from './config'
export { setFocusHandler } from './setFocusHandler'
export { useIsFetching } from './useIsFetching'
Expand Down
7 changes: 6 additions & 1 deletion src/index.production.js
@@ -1,4 +1,9 @@
export { queryCache } from './queryCache'
export {
queryCache,
makeQueryCache,
ReactQueryCacheProvider,
useQueryCache,
} from './queryCache'
export { ReactQueryConfigProvider } from './config'
export { setFocusHandler } from './setFocusHandler'
export { useIsFetching } from './useIsFetching'
Expand Down
41 changes: 40 additions & 1 deletion src/queryCache.js
@@ -1,3 +1,4 @@
import React from 'react'
import {
isServer,
functionalUpdate,
Expand All @@ -14,6 +15,42 @@ import { defaultConfigRef } from './config'

export const queryCache = makeQueryCache()

export const queryCacheContext = React.createContext(queryCache)

export const queryCaches = [queryCache]

export function useQueryCache() {
return React.useContext(queryCacheContext)
}

export function ReactQueryCacheProvider({ queryCache, children }) {
const cache = React.useMemo(() => queryCache || makeQueryCache(), [
queryCache,
])

React.useEffect(() => {
queryCaches.push(cache)

return () => {
// remove the cache from the active list
const i = queryCaches.indexOf(cache)
if (i >= 0) {
queryCaches.splice(i, 1)
}
// if the cache was created by us, we need to tear it down
if (queryCache == null) {
cache.clear()
}
}
}, [cache, queryCache])

return (
<queryCacheContext.Provider value={cache}>
{children}
</queryCacheContext.Provider>
)
}

const actionInit = {}
const actionFailed = {}
const actionMarkStale = {}
Expand All @@ -32,7 +69,7 @@ export function makeQueryCache() {
}

const notifyGlobalListeners = () => {
cache.isFetching = Object.values(queryCache.queries).reduce(
cache.isFetching = Object.values(cache.queries).reduce(
(acc, query) => (query.state.isFetching ? acc + 1 : acc),
0
)
Expand Down Expand Up @@ -129,6 +166,7 @@ export function makeQueryCache() {
query.config = { ...query.config, ...config }
} else {
query = makeQuery({
cache,
queryKey,
queryHash,
queryVariables,
Expand Down Expand Up @@ -212,6 +250,7 @@ export function makeQueryCache() {
}

function makeQuery(options) {
const queryCache = options.cache
const reducer = options.config.queryReducer || defaultQueryReducer

const noQueryHash = typeof options.queryHash === 'undefined'
Expand Down
50 changes: 26 additions & 24 deletions src/setFocusHandler.js
@@ -1,6 +1,6 @@
import { isOnline, isDocumentVisible, Console, isServer } from './utils'
import { defaultConfigRef } from './config'
import { queryCache } from './queryCache'
import { queryCaches } from './queryCache'

const visibilityChangeEvent = 'visibilitychange'
const focusEvent = 'focus'
Expand All @@ -9,29 +9,31 @@ const onWindowFocus = () => {
const { refetchAllOnWindowFocus } = defaultConfigRef.current

if (isDocumentVisible() && isOnline()) {
queryCache
.refetchQueries(query => {
if (!query.instances.length) {
return false
}

if (query.config.manual === true) {
return false
}

if (query.shouldContinueRetryOnFocus) {
// delete promise, so `fetch` will create new one
delete query.promise
return true
}

if (typeof query.config.refetchOnWindowFocus === 'undefined') {
return refetchAllOnWindowFocus
} else {
return query.config.refetchOnWindowFocus
}
})
.catch(Console.error)
queryCaches.forEach(queryCache =>
queryCache
.refetchQueries(query => {
if (!query.instances.length) {
return false
}

if (query.config.manual === true) {
return false
}

if (query.shouldContinueRetryOnFocus) {
// delete promise, so `fetch` will create new one
delete query.promise
return true
}

if (typeof query.config.refetchOnWindowFocus === 'undefined') {
return refetchAllOnWindowFocus
} else {
return query.config.refetchOnWindowFocus
}
})
.catch(Console.error)
)
}
}

Expand Down

0 comments on commit 3ef9c7c

Please sign in to comment.