Server: Phase 2 (REVIEW not respected yet)

This commit is contained in:
Thomas Karner committed 2026-09-21 11:24:43 +02:00
1 parent 5d16ded553
commit 142b47674d
4271 files changed
+1203269

No files matched your search

@@ -0,0 +1,208 @@
module.exports = ({ root, jscodeshift }) => {
const findImportIdentifierOf = (importSpecifiers, identifier) => {
const specifier = importSpecifiers
.filter((node) => node.value.imported.name === identifier)
.paths()
if (specifier.length > 0) {
return specifier[0].value.local
}
return jscodeshift.identifier(identifier)
}
const findImportSpecifiers = (packageName) =>
root
.find(jscodeshift.ImportDeclaration, {
source: {
value: packageName,
},
})
.find(jscodeshift.ImportSpecifier, {})
const locateImports = (
identifiers,
packageName = '@tanstack/react-query',
) => {
const findNamespaceImportIdentifier = () => {
const specifier = root
.find(jscodeshift.ImportDeclaration, {
source: {
value: packageName,
},
})
.find(jscodeshift.ImportNamespaceSpecifier)
.paths()
return specifier.length > 0 ? specifier[0].value.local : null
}
/**
* First, we search for the namespace import identifier because if we have any, we assume the consumer uses
* namespace imports. In this case, we won't search for named imports at all.
*/
const namespaceImportIdentifier = findNamespaceImportIdentifier()
if (namespaceImportIdentifier) {
const identifierMap = {}
for (const identifier of identifiers) {
identifierMap[identifier] = jscodeshift.identifier(identifier)
}
return {
namespace: namespaceImportIdentifier,
...identifierMap,
}
}
const importSpecifiers = findImportSpecifiers(packageName)
const identifierMap = {}
for (const identifier of identifiers) {
identifierMap[identifier] = findImportIdentifierOf(
importSpecifiers,
identifier,
)
}
return {
namespace: null,
...identifierMap,
}
}
const findAllMethodCalls = () =>
root
// First, we need to find all method calls.
.find(jscodeshift.CallExpression, {
callee: {
type: jscodeshift.MemberExpression.name,
property: {
type: jscodeshift.Identifier.name,
},
},
})
const findQueryClientIdentifiers = (importIdentifiers) =>
root
.find(jscodeshift.VariableDeclarator, {})
.filter((node) => {
if (node.value.init) {
const initializer = node.value.init
return (
isClassInstantiationOf(
initializer,
getSelectorByImports(importIdentifiers, 'QueryClient'),
) ||
isFunctionCallOf(
initializer,
getSelectorByImports(importIdentifiers, 'useQueryClient'),
)
)
}
return false
})
.paths()
.map((node) => node.value.id.name)
const isCallExpression = (node) =>
jscodeshift.match(node, { type: jscodeshift.CallExpression.name })
const isIdentifier = (node) =>
jscodeshift.match(node, { type: jscodeshift.Identifier.name })
const isMemberExpression = (node) =>
jscodeshift.match(node, { type: jscodeshift.MemberExpression.name })
const isNewExpression = (node) =>
jscodeshift.match(node, { type: jscodeshift.NewExpression.name })
const isArrayExpression = (node) =>
jscodeshift.match(node, { type: jscodeshift.ArrayExpression.name })
const isObjectExpression = (node) =>
jscodeshift.match(node, { type: jscodeshift.ObjectExpression.name })
const isObjectProperty = (node) =>
jscodeshift.match(node, { type: jscodeshift.ObjectProperty.name })
const isSpreadElement = (node) =>
jscodeshift.match(node, { type: jscodeshift.SpreadElement.name })
/**
* @param {import('jscodeshift').Node} node
* @returns {boolean}
*/
const isFunctionDefinition = (node) => {
const isArrowFunctionExpression = jscodeshift.match(node, {
type: jscodeshift.ArrowFunctionExpression.name,
})
const isFunctionExpression = jscodeshift.match(node, {
type: jscodeshift.FunctionExpression.name,
})
return isArrowFunctionExpression || isFunctionExpression
}
const warn = (message) => {
if (process.env.NODE_ENV !== 'test') {
console.warn(message)
}
}
const isClassInstantiationOf = (node, selector) => {
if (!isNewExpression(node)) {
return false
}
const parts = selector.split('.')
return parts.length === 1
? isIdentifier(node.callee) && node.callee.name === parts[0]
: isMemberExpression(node.callee) &&
node.callee.object.name === parts[0] &&
node.callee.property.name === parts[1]
}
const isFunctionCallOf = (node, selector) => {
if (!isCallExpression(node)) {
return false
}
const parts = selector.split('.')
return parts.length === 1
? isIdentifier(node.callee) && node.callee.name === parts[0]
: isMemberExpression(node.callee) &&
node.callee.object.name === parts[0] &&
node.callee.property.name === parts[1]
}
const getSelectorByImports = (imports, path) =>
imports.namespace
? `${imports.namespace.name}.${imports[path].name}`
: imports[path].name
return {
findAllMethodCalls,
getSelectorByImports,
isCallExpression,
isClassInstantiationOf,
isFunctionCallOf,
isIdentifier,
isMemberExpression,
isArrayExpression,
isObjectExpression,
isObjectProperty,
isSpreadElement,
isFunctionDefinition,
locateImports,
warn,
queryClient: {
findQueryClientIdentifiers,
},
}
}
@@ -0,0 +1,124 @@
module.exports = ({
jscodeshift,
utils,
root,
packageName = '@tanstack/react-query',
}) => {
const isGetQueryCacheMethodCall = (
initializer,
importIdentifiers,
knownQueryClientIds,
) => {
const isKnownQueryClient = (node) =>
utils.isIdentifier(node) && knownQueryClientIds.includes(node.name)
const isGetQueryCacheIdentifier = (node) =>
utils.isIdentifier(node) && node.name === 'getQueryCache'
const isValidInitializer = (node) =>
utils.isCallExpression(node) && utils.isMemberExpression(node.callee)
if (isValidInitializer(initializer)) {
const instance = initializer.callee.object
return (
isGetQueryCacheIdentifier(initializer.callee.property) &&
(isKnownQueryClient(instance) ||
utils.isFunctionCallOf(
instance,
utils.getSelectorByImports(importIdentifiers, 'useQueryClient'),
))
)
}
return false
}
const findQueryCacheInstantiations = (
importIdentifiers,
knownQueryClientIds,
) =>
root.find(jscodeshift.VariableDeclarator, {}).filter((node) => {
if (node.value.init) {
const initializer = node.value.init
return (
utils.isClassInstantiationOf(
initializer,
utils.getSelectorByImports(importIdentifiers, 'QueryCache'),
) ||
isGetQueryCacheMethodCall(
initializer,
importIdentifiers,
knownQueryClientIds,
)
)
}
return false
})
const filterQueryCacheMethodCalls = (node) =>
utils.isIdentifier(node) && ['find', 'findAll'].includes(node.name)
const findQueryCacheMethodCalls = (importIdentifiers) => {
/**
* Here we collect all query client instantiations. We have to make aware of them because the query cache can be
* accessed by the query client as well.
*/
const queryClientIdentifiers =
utils.queryClient.findQueryClientIdentifiers(importIdentifiers)
/**
* Here we collect all query cache instantiations. The reason is simple: the methods can be called on query cache
* instances, to locate the possible usages we need to be aware of the identifier names.
*/
const queryCacheIdentifiers = findQueryCacheInstantiations(
importIdentifiers,
queryClientIdentifiers,
)
.paths()
.map((node) => node.value.id.name)
return (
utils
// First, we need to find all method calls.
.findAllMethodCalls()
// Then we narrow the collection to all `fetch` and `fetchAll` methods.
.filter((node) =>
filterQueryCacheMethodCalls(node.value.callee.property),
)
.filter((node) => {
const object = node.value.callee.object
// If the method is called on a `QueryCache` instance, we keep it in the collection.
if (utils.isIdentifier(object)) {
return queryCacheIdentifiers.includes(object.name)
}
// If the method is called on a `QueryClient` instance, we keep it in the collection.
if (utils.isCallExpression(object)) {
return isGetQueryCacheMethodCall(
object,
importIdentifiers,
queryClientIdentifiers,
)
}
return false
})
)
}
const execute = (replacer) => {
findQueryCacheMethodCalls(
utils.locateImports(
['QueryCache', 'QueryClient', 'useQueryClient'],
packageName,
),
).replaceWith(replacer)
}
return {
execute,
}
}
@@ -0,0 +1,53 @@
module.exports = ({
jscodeshift,
utils,
root,
packageName = '@tanstack/react-query',
}) => {
const filterQueryClientMethodCalls = (node, methods) =>
utils.isIdentifier(node) && methods.includes(node.name)
const findQueryClientMethodCalls = (importIdentifiers, methods) => {
/**
* Here we collect all query client instantiations. We have to make aware of them because some method calls might
* be invoked on these instances.
*/
const queryClientIdentifiers =
utils.queryClient.findQueryClientIdentifiers(importIdentifiers)
return (
utils
// First, we need to find all method calls.
.findAllMethodCalls()
// Then we narrow the collection to `QueryClient` methods.
.filter((node) =>
filterQueryClientMethodCalls(node.value.callee.property, methods),
)
.filter((node) => {
const object = node.value.callee.object
// If the method is called on a `QueryClient` instance, we keep it in the collection.
if (utils.isIdentifier(object)) {
return queryClientIdentifiers.includes(object.name)
}
// If the method is called on the return value of `useQueryClient` hook, we keep it in the collection.
return utils.isFunctionCallOf(
object,
utils.getSelectorByImports(importIdentifiers, 'useQueryClient'),
)
})
)
}
const execute = (methods, replacer) => {
findQueryClientMethodCalls(
utils.locateImports(['QueryClient', 'useQueryClient'], packageName),
methods,
).replaceWith(replacer)
}
return {
execute,
}
}
@@ -0,0 +1,38 @@
module.exports = ({
jscodeshift,
utils,
root,
packageName = '@tanstack/react-query',
}) => {
const filterUseQueryLikeHookCalls = (node, importIdentifiers, hooks) => {
for (const hook of hooks) {
const selector = utils.getSelectorByImports(importIdentifiers, hook)
if (utils.isFunctionCallOf(node, selector)) {
return true
}
}
return false
}
const findUseQueryLikeHookCalls = (importIdentifiers, hooks) =>
root
// First, we need to find all call expressions.
.find(jscodeshift.CallExpression, {})
// Then we narrow the collection to the `useQuery` like hook calls.
.filter((node) =>
filterUseQueryLikeHookCalls(node.value, importIdentifiers, hooks),
)
const execute = (hooks, replacer) => {
findUseQueryLikeHookCalls(
utils.locateImports(hooks, packageName),
hooks,
).replaceWith(replacer)
}
return {
execute,
}
}
@@ -0,0 +1,181 @@
const createUtilsObject = require('../utils/index.cjs')
const createKeyReplacer = require('./utils/replacers/key-replacer.cjs')
const createUseQueryLikeTransformer = require('../utils/transformers/use-query-like-transformer.cjs')
const createQueryClientTransformer = require('../utils/transformers/query-client-transformer.cjs')
const createQueryCacheTransformer = require('../utils/transformers/query-cache-transformer.cjs')
const transformQueryClientUsages = ({
jscodeshift,
utils,
root,
filePath,
packageName,
}) => {
const transformer = createQueryClientTransformer({
jscodeshift,
utils,
root,
packageName,
})
const replacer = createKeyReplacer({ jscodeshift, root, filePath })
transformer.execute(
[
// Not object syntax-aware methods.
'getMutationDefaults',
'getQueriesData',
'getQueryData',
'getQueryDefaults',
'getQueryState',
'isFetching',
'setMutationDefaults',
'setQueriesData',
'setQueryData',
'setQueryDefaults',
// Object syntax-aware methods.
'cancelQueries',
'fetchInfiniteQuery',
'fetchQuery',
'invalidateQueries',
'prefetchInfiniteQuery',
'prefetchQuery',
'refetchQueries',
'removeQueries',
'resetQueries',
],
replacer,
)
}
const transformUseQueriesUsages = ({
jscodeshift,
utils,
root,
packageName,
}) => {
const transformer = createUseQueryLikeTransformer({
jscodeshift,
utils,
root,
packageName,
})
const replacer = ({ node }) => {
/**
* When the node doesn't have the 'original' property, that means the codemod has been already applied,
* so we don't need to do any changes.
*/
if (!node.original) {
return node
}
const newCallExpression = jscodeshift.callExpression(node.original.callee, [
jscodeshift.objectExpression([
jscodeshift.property(
'init',
jscodeshift.identifier('queries'),
node.original.arguments[0],
),
]),
])
// TODO: This should be part of one function!
if (node.typeParameters) {
newCallExpression.typeArguments = node.typeParameters
}
return newCallExpression
}
transformer.execute(['useQueries'], replacer)
}
const transformUseQueryLikeUsages = ({
jscodeshift,
utils,
root,
filePath,
packageName,
}) => {
const transformer = createUseQueryLikeTransformer({
jscodeshift,
utils,
root,
packageName,
})
transformer.execute(
['useQuery', 'useInfiniteQuery', 'useIsFetching', 'useIsMutating'],
createKeyReplacer({
jscodeshift,
root,
filePath,
keyName: 'queryKey',
}),
)
transformer.execute(
['useMutation'],
createKeyReplacer({
jscodeshift,
root,
filePath,
keyName: 'mutationKey',
}),
)
}
const transformQueryCacheUsages = ({
jscodeshift,
utils,
root,
filePath,
packageName,
}) => {
const transformer = createQueryCacheTransformer({
jscodeshift,
utils,
root,
packageName,
})
const replacer = createKeyReplacer({ jscodeshift, root, filePath })
transformer.execute(replacer)
}
module.exports = (file, api) => {
const jscodeshift = api.jscodeshift
const root = jscodeshift(file.source)
// TODO: Execute the transformers only when it contains a `react-query` import!
const utils = createUtilsObject({ root, jscodeshift })
const filePath = file.path
const packageName = 'react-query'
// This function transforms usages like `useQuery` and `useMutation`.
transformUseQueryLikeUsages({
jscodeshift,
utils,
root,
filePath,
packageName,
})
// This function transforms usages of `useQueries`.
transformUseQueriesUsages({
jscodeshift,
utils,
root,
packageName,
})
// This function transforms usages of `QueryClient`.
transformQueryClientUsages({
jscodeshift,
utils,
root,
filePath,
packageName,
})
// This function transforms usages of `QueryCache`.
transformQueryCacheUsages({ jscodeshift, utils, root, filePath, packageName })
return root.toSource({ quote: 'single', lineTerminator: '\n' })
}
@@ -0,0 +1,25 @@
module.exports = (file, api) => {
const jscodeshift = api.jscodeshift
const root = jscodeshift(file.source)
const replacements = [
{ from: 'react-query', to: '@tanstack/react-query' },
{ from: 'react-query/devtools', to: '@tanstack/react-query-devtools' },
]
replacements.forEach(({ from, to }) => {
root
.find(jscodeshift.ImportDeclaration, {
source: {
value: from,
},
})
.replaceWith(({ node }) => {
node.source.value = to
return node
})
})
return root.toSource({ quote: 'single', lineTerminator: '\n' })
}
@@ -0,0 +1,164 @@
class UnprocessableKeyError extends Error {
constructor(message) {
super(message)
this.name = 'UnprocessableKeyError'
}
}
module.exports = ({ jscodeshift, root, filePath, keyName = 'queryKey' }) => {
const isArrayExpression = (node) =>
jscodeshift.match(node, { type: jscodeshift.ArrayExpression.name })
const isStringLiteral = (node) =>
jscodeshift.match(node, { type: jscodeshift.StringLiteral.name }) ||
jscodeshift.match(node, { type: jscodeshift.Literal.name })
const isTemplateLiteral = (node) =>
jscodeshift.match(node, { type: jscodeshift.TemplateLiteral.name })
const findVariableDeclaration = (node) => {
const declarations = root
.find(jscodeshift.VariableDeclarator, {
id: {
type: jscodeshift.Identifier.name,
name: node.name,
},
})
.paths()
return declarations.length > 0 ? declarations[0] : null
}
const createKeyValue = (node) => {
// When the node is a string literal we convert it into an array of strings.
if (isStringLiteral(node)) {
return jscodeshift.arrayExpression([
jscodeshift.stringLiteral(node.value),
])
}
// When the node is a template literal we convert it into an array of template literals.
if (isTemplateLiteral(node)) {
return jscodeshift.arrayExpression([
jscodeshift.templateLiteral(node.quasis, node.expressions),
])
}
if (jscodeshift.match(node, { type: jscodeshift.Identifier.name })) {
// When the node is an identifier at first, we try to find its declaration, because we will try
// to guess its type.
const variableDeclaration = findVariableDeclaration(node)
if (!variableDeclaration) {
throw new UnprocessableKeyError(
`In file ${filePath} at line ${node.loc.start.line} the type of identifier \`${node.name}\` couldn't be recognized, so the codemod couldn't be applied. Please migrate manually.`,
)
}
const initializer = variableDeclaration.value.init
// When it's a string, we just wrap it into an array expression.
if (isStringLiteral(initializer) || isTemplateLiteral(initializer)) {
return jscodeshift.arrayExpression([node])
}
}
throw new UnprocessableKeyError(
`In file ${filePath} at line ${node.loc.start.line} the type of the \`${keyName}\` couldn't be recognized, so the codemod couldn't be applied. Please migrate manually.`,
)
}
const createKeyProperty = (node) =>
jscodeshift.property(
'init',
jscodeshift.identifier(keyName),
createKeyValue(node),
)
const getPropertyFromObjectExpression = (objectExpression, propertyName) =>
objectExpression.properties.find(
(property) => property.key.name === propertyName,
) ?? null
const buildWithTypeArguments = (node, builder) => {
const newNode = builder(node)
if (node.typeParameters) {
newNode.typeArguments = node.typeParameters
}
return newNode
}
return ({ node }) => {
// When the node doesn't have the 'original' property, that means the codemod has been already applied,
// so we don't need to do any changes.
if (!node.original) {
return node
}
const methodArguments = node.arguments
// The method call doesn't have any arguments, we have nothing to do in this case.
if (methodArguments.length === 0) {
return node
}
try {
const [firstArgument, ...restOfTheArguments] = methodArguments
if (
jscodeshift.match(firstArgument, {
type: jscodeshift.ObjectExpression.name,
})
) {
const originalKey = getPropertyFromObjectExpression(
firstArgument,
keyName,
)
if (!originalKey) {
throw new UnprocessableKeyError(
`In file ${filePath} at line ${node.loc.start.line} the \`${keyName}\` couldn't be found. Did you forget to add it?`,
)
}
const restOfTheProperties = firstArgument.properties.filter(
(item) => item.key.name !== keyName,
)
return buildWithTypeArguments(node, (originalNode) =>
jscodeshift.callExpression(originalNode.original.callee, [
jscodeshift.objectExpression([
createKeyProperty(originalKey.value),
...restOfTheProperties,
]),
...restOfTheArguments,
]),
)
}
// When the node is an array expression we just simply return it because we want query keys to be arrays.
if (isArrayExpression(firstArgument)) {
return node
}
return buildWithTypeArguments(node, (originalNode) =>
jscodeshift.callExpression(originalNode.original.callee, [
createKeyValue(firstArgument),
...restOfTheArguments,
]),
)
} catch (error) {
if (error.name === 'UnprocessableKeyError') {
if (process.env.NODE_ENV !== 'test') {
console.warn(error.message)
}
return node
}
throw error
}
}
}
@@ -0,0 +1,244 @@
const createUtilsObject = require('../../utils/index.cjs')
const createUseQueryLikeTransformer = require('../../utils/transformers/use-query-like-transformer.cjs')
const createQueryClientTransformer = require('../../utils/transformers/query-client-transformer.cjs')
const originalName = 'isLoading'
const newName = 'isPending'
/**
* @param {import('jscodeshift')} jscodeshift
* @param {Object} utils
* @param {import('jscodeshift').Collection} root
* @param {string} filePath
* @param {{keyName: "mutationKey"|"queryKey", queryClientMethods: ReadonlyArray<string>, hooks: ReadonlyArray<string>}} config
*/
const transformUsages = ({ jscodeshift, utils, root, filePath, config }) => {
/**
* @param {import('jscodeshift').CallExpression | import('jscodeshift').ExpressionStatement} node
* @returns {{start: number, end: number}}
*/
const getNodeLocation = (node) => {
const location = utils.isCallExpression(node) ? node.callee.loc : node.loc
const start = location.start.line
const end = location.end.line
return { start, end }
}
/**
* @param {import('jscodeshift').ASTNode} node
* @returns {boolean}
*/
const isObjectExpression = (node) => {
return jscodeshift.match(node, {
type: jscodeshift.ObjectExpression.name,
})
}
/**
* @param {import('jscodeshift').ASTNode} node
* @returns {boolean}
*/
const isObjectPattern = (node) => {
return jscodeshift.match(node, {
type: jscodeshift.ObjectPattern.name,
})
}
/**
* @param {import('jscodeshift').ASTNode} node
* @returns {boolean}
*/
const isVariableDeclarator = (node) => {
return jscodeshift.match(node, {
type: jscodeshift.VariableDeclarator.name,
})
}
/**
* @param {import('jscodeshift').Node} node
* @param {import('jscodeshift').Identifier} identifier
* @returns {Collection<import('jscodeshift').MemberExpression>}
*/
const findIsLoadingPropertiesOfIdentifier = (node, identifier) => {
return jscodeshift(node).find(jscodeshift.MemberExpression, {
object: {
type: jscodeshift.Identifier.name,
name: identifier.name,
},
property: {
type: jscodeshift.Identifier.name,
name: originalName,
},
})
}
/**
* @param {import('jscodeshift').ObjectPattern} node
* @returns {import('jscodeshift').ObjectProperty|null}
*/
const findIsLoadingObjectPropertyInObjectPattern = (node) => {
return (
node.properties.find((property) =>
jscodeshift.match(property, {
key: {
type: jscodeshift.Identifier.name,
name: originalName,
},
}),
) ?? null
)
}
/**
* @param {import('jscodeshift').ObjectPattern} node
* @returns {import('jscodeshift').RestElement|null}
*/
const findRestElementInObjectPattern = (node) => {
return (
node.properties.find((property) =>
jscodeshift.match(property, {
type: jscodeshift.RestElement.name,
}),
) ?? null
)
}
const replacer = (path, transformNode) => {
const node = path.node
const parentNode = path.parentPath.value
const { start, end } = getNodeLocation(node)
try {
if (!isVariableDeclarator(parentNode)) {
// The parent node is not a variable declarator, the transformation will be skipped.
return node
}
const lookupNode = path.scope.node
const variableDeclaratorId = parentNode.id
if (isObjectPattern(variableDeclaratorId)) {
const isLoadingObjectProperty =
findIsLoadingObjectPropertyInObjectPattern(variableDeclaratorId)
if (isLoadingObjectProperty) {
jscodeshift(lookupNode)
.find(jscodeshift.ObjectProperty, {
key: {
type: jscodeshift.Identifier.name,
name: originalName,
},
})
.replaceWith((mutablePath) => {
if (isObjectPattern(mutablePath.parent)) {
const affectedProperty = mutablePath.value.value.shorthand
? 'value'
: 'key'
mutablePath.value[affectedProperty].name = newName
return mutablePath.value
}
if (isObjectExpression(mutablePath.parent)) {
const affectedProperty = mutablePath.value.value.shorthand
? 'key'
: 'value'
mutablePath.value[affectedProperty].name = newName
return mutablePath.value
}
return mutablePath.value
})
// Renaming all other 'isLoading' references that are object properties.
jscodeshift(lookupNode)
.find(jscodeshift.Identifier, { name: originalName })
.replaceWith((mutablePath) => {
if (
!jscodeshift.match(mutablePath.parent, {
type: jscodeshift.ObjectProperty.name,
})
) {
mutablePath.value.name = newName
}
return mutablePath.value
})
}
const restElement = findRestElementInObjectPattern(variableDeclaratorId)
if (restElement) {
findIsLoadingPropertiesOfIdentifier(
lookupNode,
restElement.argument,
).replaceWith(({ node: mutableNode }) => {
mutableNode.property.name = newName
return mutableNode
})
}
return node
}
if (utils.isIdentifier(variableDeclaratorId)) {
findIsLoadingPropertiesOfIdentifier(
lookupNode,
variableDeclaratorId,
).replaceWith(({ node: mutableNode }) => {
mutableNode.property.name = newName
return mutableNode
})
return node
}
utils.warn(
`The usage in file "${filePath}" at line ${start}:${end} could not be transformed. Please migrate this usage manually.`,
)
return node
} catch (error) {
utils.warn(
`An unknown error occurred while processing the "${filePath}" file. Please review this file, because the codemod couldn't be applied.`,
)
return node
}
}
createUseQueryLikeTransformer({ jscodeshift, utils, root }).execute(
config.hooks,
replacer,
)
createQueryClientTransformer({ jscodeshift, utils, root }).execute(
config.queryClientMethods,
replacer,
)
}
module.exports = (file, api) => {
const jscodeshift = api.jscodeshift
const root = jscodeshift(file.source)
const utils = createUtilsObject({ root, jscodeshift })
const filePath = file.path
const dependencies = { jscodeshift, utils, root, filePath }
transformUsages({
...dependencies,
config: {
hooks: ['useQuery', 'useMutation'],
queryClientMethods: [],
},
})
return root.toSource({ quote: 'single', lineTerminator: '\n' })
}
@@ -0,0 +1,32 @@
### Intro
The prerequisite for this code mod is to migrate your usages to the new syntax, so overloads for hooks and `QueryClient` methods shouldn't be available anymore.
### Affected usages
Please note, this code mod transforms usages only where the first argument is an object expression.
The following usage should be transformed by the code mod:
```ts
const { data } = useQuery({
queryKey: ['posts'],
queryFn: queryFn,
keepPreviousData: true,
})
```
But the following usage won't be transformed by the code mod, because the first argument an identifier:
```ts
const hookArgument = {
queryKey: ['posts'],
queryFn: queryFn,
keepPreviousData: true,
}
const { data } = useQuery(hookArgument)
```
### Troubleshooting
In case of any errors, feel free to reach us out via Discord or open an issue. If you open an issue, please provide a code snippet as well, because without a snippet we cannot find the bug in the code mod.
@@ -0,0 +1,271 @@
const createUtilsObject = require('../../utils/index.cjs')
const createUseQueryLikeTransformer = require('../../utils/transformers/use-query-like-transformer.cjs')
const createQueryClientTransformer = require('../../utils/transformers/query-client-transformer.cjs')
const AlreadyHasPlaceholderDataProperty = require('./utils/already-has-placeholder-data-property.cjs')
/**
* @param {import('jscodeshift')} jscodeshift
* @param {Object} utils
* @param {import('jscodeshift').Collection} root
* @param {string} filePath
* @param {{keyName: "mutationKey"|"queryKey", queryClientMethods: ReadonlyArray<string>, hooks: ReadonlyArray<string>}} config
*/
const transformUsages = ({ jscodeshift, utils, root, filePath, config }) => {
/**
* @param {import('jscodeshift').CallExpression | import('jscodeshift').ExpressionStatement} node
* @returns {{start: number, end: number}}
*/
const getNodeLocation = (node) => {
const location = utils.isCallExpression(node) ? node.callee.loc : node.loc
const start = location.start.line
const end = location.end.line
return { start, end }
}
/**
* @param {import('jscodeshift').ObjectProperty} objectProperty
* @returns {boolean}
*/
const isKeepPreviousDataObjectProperty = (objectProperty) => {
return jscodeshift.match(objectProperty.key, {
type: jscodeshift.Identifier.name,
name: 'keepPreviousData',
})
}
/**
* @param {import('jscodeshift').ObjectProperty} objectProperty
* @returns {boolean}
*/
const isObjectPropertyHasTrueBooleanLiteralValue = (objectProperty) => {
return jscodeshift.match(objectProperty.value, {
type: jscodeshift.BooleanLiteral.name,
value: true,
})
}
/**
* @param {import('jscodeshift').ObjectExpression} objectExpression
* @returns {Array<import('jscodeshift').ObjectProperty>}
*/
const filterKeepPreviousDataProperty = (objectExpression) => {
return objectExpression.properties.filter((objectProperty) => {
return !isKeepPreviousDataObjectProperty(objectProperty)
})
}
const createPlaceholderDataObjectProperty = () => {
return jscodeshift.objectProperty(
jscodeshift.identifier('placeholderData'),
jscodeshift.identifier('keepPreviousData'),
)
}
/**
* @param {import('jscodeshift').ObjectExpression} objectExpression
* @returns {boolean}
*/
const hasPlaceholderDataProperty = (objectExpression) => {
return (
objectExpression.properties.findIndex((objectProperty) => {
return jscodeshift.match(objectProperty.key, {
type: jscodeshift.Identifier.name,
name: 'placeholderData',
})
}) !== -1
)
}
/**
* @param {import('jscodeshift').ObjectExpression} objectExpression
* @returns {import('jscodeshift').ObjectProperty | undefined}
*/
const getKeepPreviousDataProperty = (objectExpression) => {
return objectExpression.properties.find(isKeepPreviousDataObjectProperty)
}
let shouldAddKeepPreviousDataImport = false
const replacer = (path, resolveTargetArgument, transformNode) => {
const node = path.node
const { start, end } = getNodeLocation(node)
try {
const targetArgument = resolveTargetArgument(node)
if (targetArgument && utils.isObjectExpression(targetArgument)) {
const isPlaceholderDataPropertyPresent =
hasPlaceholderDataProperty(targetArgument)
if (hasPlaceholderDataProperty(targetArgument)) {
throw new AlreadyHasPlaceholderDataProperty(node, filePath)
}
const keepPreviousDataProperty =
getKeepPreviousDataProperty(targetArgument)
const keepPreviousDataPropertyHasTrueValue =
isObjectPropertyHasTrueBooleanLiteralValue(keepPreviousDataProperty)
if (!keepPreviousDataPropertyHasTrueValue) {
utils.warn(
`The usage in file "${filePath}" at line ${start}:${end} already contains a "keepPreviousData" property but its value is not "true". Please migrate this usage manually.`,
)
return node
}
if (keepPreviousDataPropertyHasTrueValue) {
// Removing the `keepPreviousData` property from the object.
const mutableObjectExpressionProperties =
filterKeepPreviousDataProperty(targetArgument)
if (!isPlaceholderDataPropertyPresent) {
shouldAddKeepPreviousDataImport = true
// When the `placeholderData` property is not present, the `placeholderData: keepPreviousData` property will be added.
mutableObjectExpressionProperties.push(
createPlaceholderDataObjectProperty(),
)
}
return transformNode(
node,
jscodeshift.objectExpression(mutableObjectExpressionProperties),
)
}
}
utils.warn(
`The usage in file "${filePath}" at line ${start}:${end} could not be transformed, because the first parameter is not an object expression. Please migrate this usage manually.`,
)
return node
} catch (error) {
utils.warn(
error.name === AlreadyHasPlaceholderDataProperty.name
? error.message
: `An unknown error occurred while processing the "${filePath}" file. Please review this file, because the codemod couldn't be applied.`,
)
return node
}
}
createUseQueryLikeTransformer({ jscodeshift, utils, root }).execute(
config.hooks,
(path) => {
const resolveTargetArgument = (node) => node.arguments[0] ?? null
const transformNode = (node, transformedArgument) =>
jscodeshift.callExpression(node.original.callee, [transformedArgument])
return replacer(path, resolveTargetArgument, transformNode)
},
)
createQueryClientTransformer({ jscodeshift, utils, root }).execute(
config.queryClientMethods,
(path) => {
const resolveTargetArgument = (node) => node.arguments[1] ?? null
const transformNode = (node, transformedArgument) => {
return jscodeshift.callExpression(node.original.callee, [
node.arguments[0],
transformedArgument,
...node.arguments.slice(2, 0),
])
}
return replacer(path, resolveTargetArgument, transformNode)
},
)
const importIdentifierOfQueryClient = utils.getSelectorByImports(
utils.locateImports(['QueryClient']),
'QueryClient',
)
root
.find(jscodeshift.ExpressionStatement, {
expression: {
type: jscodeshift.NewExpression.name,
callee: {
type: jscodeshift.Identifier.name,
name: importIdentifierOfQueryClient,
},
},
})
.filter((path) => path.node.expression)
.replaceWith((path) => {
const resolveTargetArgument = (node) => {
const paths = jscodeshift(node)
.find(jscodeshift.ObjectProperty, {
key: {
type: jscodeshift.Identifier.name,
name: 'keepPreviousData',
},
})
.paths()
return paths.length > 0 ? paths[0].parent.node : null
}
const transformNode = (node, transformedArgument) => {
jscodeshift(node.expression)
.find(jscodeshift.ObjectProperty, {
key: {
type: jscodeshift.Identifier.name,
name: 'queries',
},
})
.replaceWith(({ node: mutableNode }) => {
mutableNode.value.properties = transformedArgument.properties
return mutableNode
})
return node
}
return replacer(path, resolveTargetArgument, transformNode)
})
return { shouldAddKeepPreviousDataImport }
}
module.exports = (file, api) => {
const jscodeshift = api.jscodeshift
const root = jscodeshift(file.source)
const utils = createUtilsObject({ root, jscodeshift })
const filePath = file.path
const dependencies = { jscodeshift, utils, root, filePath }
const { shouldAddKeepPreviousDataImport } = transformUsages({
...dependencies,
config: {
hooks: ['useInfiniteQuery', 'useQueries', 'useQuery'],
queryClientMethods: ['setQueryDefaults'],
},
})
if (shouldAddKeepPreviousDataImport) {
root
.find(jscodeshift.ImportDeclaration, {
source: {
value: '@tanstack/react-query',
},
})
.replaceWith(({ node: mutableNode }) => {
mutableNode.specifiers = [
jscodeshift.importSpecifier(
jscodeshift.identifier('keepPreviousData'),
),
...mutableNode.specifiers,
]
return mutableNode
})
}
return root.toSource({ quote: 'single', lineTerminator: '\n' })
}
@@ -0,0 +1,26 @@
class AlreadyHasPlaceholderDataProperty extends Error {
/**
* @param {import('jscodeshift').CallExpression} callExpression
* @param {string} filePath
*/
constructor(callExpression, filePath) {
super('')
this.message = this.buildMessage(callExpression, filePath)
this.name = 'AlreadyHasPlaceholderDataProperty'
}
/**
* @param {import('jscodeshift').CallExpression} callExpression
* @param {string} filePath
* @returns {string}
*/
buildMessage(callExpression, filePath) {
const location = callExpression.callee.loc
const start = location.start.line
const end = location.end.line
return `The usage in file "${filePath}" at line ${start}:${end} already contains a "placeholderData" property. Please migrate this usage manually.`
}
}
module.exports = AlreadyHasPlaceholderDataProperty
@@ -0,0 +1,58 @@
const createUtilsObject = require('../../utils/index.cjs')
const transformFilterAwareUsages = require('./transformers/filter-aware-usage-transformer.cjs')
const transformQueryFnAwareUsages = require('./transformers/query-fn-aware-usage-transformer.cjs')
module.exports = (file, api) => {
const jscodeshift = api.jscodeshift
const root = jscodeshift(file.source)
const utils = createUtilsObject({ root, jscodeshift })
const filePath = file.path
const dependencies = { jscodeshift, utils, root, filePath }
transformFilterAwareUsages({
...dependencies,
config: {
keyName: 'queryKey',
fnName: 'queryFn',
queryClientMethods: [
'cancelQueries',
'getQueriesData',
'invalidateQueries',
'isFetching',
'refetchQueries',
'removeQueries',
'resetQueries',
// 'setQueriesData',
],
hooks: ['useIsFetching', 'useQuery'],
},
})
transformFilterAwareUsages({
...dependencies,
config: {
keyName: 'mutationKey',
fnName: 'mutationFn',
queryClientMethods: [],
hooks: ['useIsMutating', 'useMutation'],
},
})
transformQueryFnAwareUsages({
...dependencies,
config: {
keyName: 'queryKey',
queryClientMethods: [
'ensureQueryData',
'fetchQuery',
'prefetchQuery',
'fetchInfiniteQuery',
'prefetchInfiniteQuery',
],
hooks: [],
},
})
return root.toSource({ quote: 'single', lineTerminator: '\n' })
}
@@ -0,0 +1,271 @@
const createV5UtilsObject = require('../utils/index.cjs')
const UnknownUsageError = require('../utils/unknown-usage-error.cjs')
const createQueryClientTransformer = require('../../../utils/transformers/query-client-transformer.cjs')
const createQueryCacheTransformer = require('../../../utils/transformers/query-cache-transformer.cjs')
const createUseQueryLikeTransformer = require('../../../utils/transformers/use-query-like-transformer.cjs')
/**
* @param {import('jscodeshift').api} jscodeshift
* @param {Object} utils
* @param {import('jscodeshift').Collection} root
* @param {string} filePath
* @param {{keyName: "mutationKey"|"queryKey", fnName: "mutationFn"|"queryFn", queryClientMethods: ReadonlyArray<string>, hooks: ReadonlyArray<string>}} config
*/
const transformFilterAwareUsages = ({
jscodeshift,
utils,
root,
filePath,
config,
}) => {
const v5Utils = createV5UtilsObject({ jscodeshift, utils })
/**
* @param {import('jscodeshift').CallExpression} node
* @param {"mutationKey"|"queryKey"} keyName
* @param {"mutationFn"|"queryFn"} fnName
* @returns {boolean}
*/
const canSkipReplacement = (node, keyName, fnName) => {
const callArguments = node.arguments
const hasKeyOrFnProperty = () =>
callArguments[0].properties.some(
(property) =>
utils.isObjectProperty(property) &&
property.key.name !== keyName &&
property.key.name !== fnName,
)
/**
* This call has at least one argument. If it's an object expression and contains the "queryKey" or "mutationKey"
* field, the transformation can be skipped, because it's already matching the expected signature.
*/
return (
callArguments.length > 0 &&
utils.isObjectExpression(callArguments[0]) &&
hasKeyOrFnProperty()
)
}
/**
* This function checks whether the given object property is a spread element or a property that's not named
* "queryKey" or "mutationKey".
*
* @param {import('jscodeshift').ObjectProperty} property
* @returns {boolean}
*/
const predicate = (property) => {
const isSpreadElement = utils.isSpreadElement(property)
const isObjectProperty = utils.isObjectProperty(property)
return (
isSpreadElement ||
(isObjectProperty && property.key.name !== config.keyName)
)
}
const replacer = (path) => {
const node = path.node
const isFunctionDefinition = (functionArgument) => {
if (utils.isFunctionDefinition(functionArgument)) {
return true
}
if (utils.isIdentifier(functionArgument)) {
const binding = v5Utils.getBindingFromScope(
path,
functionArgument.name,
filePath,
)
const isVariableDeclarator = jscodeshift.match(binding, {
type: jscodeshift.VariableDeclarator.name,
})
return isVariableDeclarator && utils.isFunctionDefinition(binding.init)
}
}
try {
// If the given method/function call matches certain criteria, the node doesn't need to be replaced, this step can be skipped.
if (canSkipReplacement(node, config.keyName, config.fnName)) {
return node
}
/**
* Here we attempt to determine the first parameter of the function call.
* If it's a function definition, we can create an object property from it (the mutation fn).
*/
const firstArgument = node.arguments[0]
if (isFunctionDefinition(firstArgument)) {
const objectExpression = jscodeshift.objectExpression([
jscodeshift.property(
'init',
jscodeshift.identifier(config.fnName),
firstArgument,
),
])
const secondArgument = node.arguments[1]
if (secondArgument) {
// If it's an object expression, we can copy the properties from it to the newly created object expression.
if (utils.isObjectExpression(secondArgument)) {
v5Utils.copyPropertiesFromSource(
secondArgument,
objectExpression,
predicate,
)
} else {
// Otherwise, we simply spread the second argument in the newly created object expression.
objectExpression.properties.push(
jscodeshift.spreadElement(secondArgument),
)
}
}
return jscodeshift.callExpression(node.original.callee, [
objectExpression,
])
}
/**
* If, instead, the first parameter is an array expression or an identifier that references
* an array expression, then we create an object property from it (the query or mutation key).
*
* @type {import('jscodeshift').Property|undefined}
*/
const keyProperty = v5Utils.transformArgumentToKey(
path,
node.arguments[0],
config.keyName,
filePath,
)
/**
* The first parameter couldn't be transformed into an object property, so it's time to throw an exception,
* it will notify the consumers that they need to rewrite this usage manually.
*/
if (!keyProperty) {
const secondArgument =
node.arguments.length > 1 ? node.arguments[1] : null
if (!secondArgument) {
throw new UnknownUsageError(node, filePath)
}
if (utils.isFunctionDefinition(secondArgument)) {
const originalArguments = node.arguments
const firstArgument = jscodeshift.objectExpression([
jscodeshift.property(
'init',
jscodeshift.identifier(config.keyName),
originalArguments[0],
),
jscodeshift.property(
'init',
jscodeshift.identifier(config.fnName),
secondArgument,
),
])
return jscodeshift.callExpression(node.original.callee, [
firstArgument,
...originalArguments.slice(2),
])
}
}
const functionArguments = [jscodeshift.objectExpression([keyProperty])]
const secondParameter = node.arguments[1]
if (secondParameter) {
const createdObjectExpression = functionArguments[0]
if (isFunctionDefinition(secondParameter)) {
const objectExpression = jscodeshift.objectExpression([
jscodeshift.property(
'init',
jscodeshift.identifier(config.keyName),
node.arguments[0],
),
jscodeshift.property(
'init',
jscodeshift.identifier(config.fnName),
secondParameter,
),
])
const thirdArgument = node.arguments[2]
if (thirdArgument) {
// If it's an object expression, we can copy the properties from it to the newly created object expression.
if (utils.isObjectExpression(thirdArgument)) {
v5Utils.copyPropertiesFromSource(
thirdArgument,
objectExpression,
predicate,
)
} else {
// Otherwise, we simply spread the third argument in the newly created object expression.
objectExpression.properties.push(
jscodeshift.spreadElement(thirdArgument),
)
}
}
return jscodeshift.callExpression(node.original.callee, [
objectExpression,
])
}
/**
* If it has a second argument, and it's an object expression, then we get the properties from it
* (except the "queryKey" or "mutationKey" properties), because these arguments will also be moved to the
* newly created object expression.
*/
if (utils.isObjectExpression(secondParameter)) {
v5Utils.copyPropertiesFromSource(
secondParameter,
createdObjectExpression,
predicate,
)
} else {
// Otherwise, we simply spread the second parameter in the newly created object expression.
createdObjectExpression.properties.push(
jscodeshift.spreadElement(secondParameter),
)
}
}
// The rest of the function arguments can be simply pushed to the function arguments object so all will be kept.
functionArguments.push(...node.arguments.slice(2))
return jscodeshift.callExpression(node.original.callee, functionArguments)
} catch (error) {
utils.warn(
error.name === UnknownUsageError.name
? error.message
: `An unknown error occurred while processing the "${filePath}" file. Please review this file, because the codemod couldn't be applied.`,
)
return node
}
}
createQueryClientTransformer({ jscodeshift, utils, root }).execute(
config.queryClientMethods,
replacer,
)
createUseQueryLikeTransformer({ jscodeshift, utils, root }).execute(
config.hooks,
replacer,
)
createQueryCacheTransformer({ jscodeshift, utils, root }).execute(replacer)
}
module.exports = transformFilterAwareUsages
@@ -0,0 +1,185 @@
const createV5UtilsObject = require('../utils/index.cjs')
const UnknownUsageError = require('../utils/unknown-usage-error.cjs')
const createQueryClientTransformer = require('../../../utils/transformers/query-client-transformer.cjs')
/**
* @param {import('jscodeshift').api} jscodeshift
* @param {Object} utils
* @param {import('jscodeshift').Collection} root
* @param {string} filePath
* @param {{keyName: "mutationKey"|"queryKey", queryClientMethods: ReadonlyArray<string>, hooks: ReadonlyArray<string>}} config
*/
const transformQueryFnAwareUsages = ({
jscodeshift,
utils,
root,
filePath,
config,
}) => {
const v5Utils = createV5UtilsObject({ jscodeshift, utils })
/**
* @param {import('jscodeshift').CallExpression} node
* @returns {boolean}
*/
const canSkipReplacement = (node) => {
const callArguments = node.arguments
const hasKeyProperty = () =>
callArguments[0].properties.some(
(property) =>
utils.isObjectProperty(property) &&
[config.keyName, 'queryFn'].includes(property.key.name),
)
return (
callArguments.length > 0 &&
utils.isObjectExpression(callArguments[0]) &&
hasKeyProperty()
)
}
const predicate = (property) => {
const isSpreadElement = utils.isSpreadElement(property)
const isObjectProperty = utils.isObjectProperty(property)
return (
isSpreadElement ||
(isObjectProperty && property.key.name !== config.keyName)
)
}
const transformArgumentToQueryFunction = (path, node) => {
const isIdentifier = utils.isIdentifier(node)
const isFunctionDefinition = utils.isFunctionDefinition(node)
if (!isIdentifier && !isFunctionDefinition) {
return undefined
}
if (isFunctionDefinition) {
return jscodeshift.property(
'init',
jscodeshift.identifier('queryFn'),
node,
)
}
const binding = v5Utils.getBindingFromScope(path, node.name, filePath)
const initializer = v5Utils.getInitializerByDeclarator(binding)
if (!utils.isFunctionDefinition(initializer)) {
return undefined
}
return jscodeshift.property(
'init',
jscodeshift.identifier('queryFn'),
binding.id,
)
}
const transformArgumentToOptionsObject = (path, node) => {
if (!utils.isIdentifier(node)) {
return undefined
}
const binding = v5Utils.getBindingFromScope(path, node.name, filePath)
const initializer = v5Utils.getInitializerByDeclarator(binding)
if (utils.isObjectExpression(initializer)) {
return jscodeshift.spreadElement(binding.id)
}
}
const replacer = (path) => {
const node = path.node
try {
// If the given method/function call matches certain criteria, the node doesn't need to be replaced, this step can be skipped.
if (canSkipReplacement(node)) {
return node
}
const keyProperty = v5Utils.transformArgumentToKey(
path,
node.arguments[0],
config.keyName,
filePath,
)
if (!keyProperty) {
throw new UnknownUsageError(node, filePath)
}
const parameters = [jscodeshift.objectExpression([keyProperty])]
const createdObjectExpression = parameters[0]
const secondParameter = node.arguments[1]
if (secondParameter) {
const queryFnProperty = transformArgumentToQueryFunction(
path,
secondParameter,
)
if (queryFnProperty) {
createdObjectExpression.properties.push(queryFnProperty)
const thirdParameter = node.arguments[2]
if (utils.isObjectExpression(thirdParameter)) {
v5Utils.copyPropertiesFromSource(
thirdParameter,
createdObjectExpression,
predicate,
)
} else {
createdObjectExpression.properties.push(
jscodeshift.spreadElement(thirdParameter),
)
}
return jscodeshift.callExpression(node.original.callee, parameters)
}
const optionsProperty = transformArgumentToOptionsObject(
path,
secondParameter,
)
if (optionsProperty) {
createdObjectExpression.properties.push(optionsProperty)
return jscodeshift.callExpression(node.original.callee, parameters)
}
if (utils.isObjectExpression(secondParameter)) {
v5Utils.copyPropertiesFromSource(
secondParameter,
createdObjectExpression,
predicate,
)
}
return jscodeshift.callExpression(node.original.callee, parameters)
}
return jscodeshift.callExpression(node.original.callee, parameters)
} catch (error) {
utils.warn(
error.name === UnknownUsageError.name
? error.message
: `An unknown error occurred while processing the "${filePath}" file. Please review this file, because the codemod couldn't be applied.`,
)
return node
}
}
createQueryClientTransformer({ jscodeshift, utils, root }).execute(
config.queryClientMethods,
replacer,
)
}
module.exports = transformQueryFnAwareUsages
@@ -0,0 +1,123 @@
const UnknownUsageError = require('./unknown-usage-error.cjs')
module.exports = ({ jscodeshift, utils }) => {
/**
*
* @param {import('jscodeshift').ObjectExpression} source
* @param {import('jscodeshift').ObjectExpression} target
* @param {(node: import('jscodeshift').Node) => boolean} predicate
*/
const copyPropertiesFromSource = (source, target, predicate) => {
source.properties.forEach((property) => {
if (predicate(property)) {
target.properties.push(property)
}
})
}
/**
* @param {import('jscodeshift').NodePath} path
* @param {string} argumentName
* @param {string} filePath
* @returns {*}
*/
const getBindingFromScope = (path, argumentName, filePath) => {
/**
* If the current scope contains the declaration then we can use the actual one else we attempt to find the
* binding from above.
*/
const scope = path.scope.declares(argumentName)
? path.scope
: path.scope.lookup(argumentName)
/**
* The declaration couldn't be found for some reason, time to move on. We warn the user it needs to be rewritten
* by themselves.
*/
if (!scope) {
return undefined
}
const binding = scope.bindings[argumentName]
.filter((item) => utils.isIdentifier(item.value))
.map((item) => item.parentPath.value)
.at(0)
if (!binding) {
throw new UnknownUsageError(path.node, filePath)
}
return binding
}
/**
* @param {import('jscodeshift').VariableDeclarator} binding
* @returns {import('jscodeshift').Node|undefined}
*/
const getInitializerByDeclarator = (binding) => {
const isVariableDeclaration = jscodeshift.match(binding, {
type: jscodeshift.VariableDeclarator.name,
})
if (!isVariableDeclaration) {
return undefined
}
const isTSAsExpression = jscodeshift.match(binding.init, {
type: jscodeshift.TSAsExpression.name,
})
return isTSAsExpression ? binding.init.expression : binding.init
}
/**
* @param {import('jscodeshift').Node} node
* @returns {boolean}
*/
const isArrayExpressionVariable = (node) =>
jscodeshift.match(node, {
type: jscodeshift.VariableDeclarator.name,
init: {
type: jscodeshift.ArrayExpression.name,
},
})
/**
* @param {import('jscodeshift').NodePath} path
* @param {import('jscodeshift').Node} node
* @param {"queryKey"|"mutationKey"} keyName
* @param {string} filePath
* @returns {import('jscodeshift').Property|undefined}
*/
const transformArgumentToKey = (path, node, keyName, filePath) => {
// If the first argument is an identifier we have to infer its type if possible.
if (utils.isIdentifier(node)) {
const binding = getBindingFromScope(path, node.name, filePath)
if (isArrayExpressionVariable(binding)) {
return jscodeshift.property(
'init',
jscodeshift.identifier(keyName),
jscodeshift.identifier(binding.id.name),
)
}
}
// If the first argument is an array, then it matches the following overload:
// methodName(queryKey?: QueryKey, firstObject?: TFirstObject, secondObject?: TSecondObject)
if (utils.isArrayExpression(node)) {
// Then we create the 'queryKey' property based on it, because it will be passed to the first argument
// that should be an object according to the new signature.
return jscodeshift.property('init', jscodeshift.identifier(keyName), node)
}
return undefined
}
return {
copyPropertiesFromSource,
getInitializerByDeclarator,
getBindingFromScope,
transformArgumentToKey,
}
}
@@ -0,0 +1,27 @@
class UnknownUsageError extends Error {
/**
* @param {import('jscodeshift').CallExpression} callExpression
* @param {string} filePath
*/
constructor(callExpression, filePath) {
super('')
this.message = this.buildMessage(callExpression, filePath)
this.name = 'UnknownUsageError'
}
/**
*
* @param {import('jscodeshift').CallExpression} callExpression
* @param {string} filePath
* @returns {string}
*/
buildMessage(callExpression, filePath) {
const location = callExpression.callee.loc
const start = location.start.line
const end = location.end.line
return `The usage in file "${filePath}" at line ${start}:${end} could not be transformed into the new syntax. Please do this manually.`
}
}
module.exports = UnknownUsageError
@@ -0,0 +1,55 @@
module.exports = (file, api) => {
const jscodeshift = api.jscodeshift
const root = jscodeshift(file.source)
const importSpecifiers = root
.find(jscodeshift.ImportDeclaration, {
source: {
value: '@tanstack/react-query',
},
})
.find(jscodeshift.ImportSpecifier, {
imported: {
name: 'Hydrate',
},
})
if (importSpecifiers.length > 0) {
const names = {
searched: 'Hydrate', // By default, we want to replace the `Hydrate` usages.
target: 'HydrationBoundary', // We want to replace them with `HydrationBoundary`.
}
importSpecifiers.replaceWith(({ node: mutableNode }) => {
/**
* When the local and imported names match which means the code doesn't contain import aliases, we need
* to replace only the import specifier.
* @type {boolean}
*/
const usesDefaultImport =
mutableNode.local.name === mutableNode.imported.name
if (!usesDefaultImport) {
// If the code uses import aliases, we must re-use the alias.
names.searched = mutableNode.local.name
names.target = mutableNode.local.name
}
// Override the import specifier.
mutableNode.imported.name = 'HydrationBoundary'
return mutableNode
})
root
.findJSXElements(names.searched)
.replaceWith(({ node: mutableNode }) => {
mutableNode.openingElement.name.name = names.target
mutableNode.closingElement.name.name = names.target
return mutableNode
})
}
return root.toSource({ quote: 'single', lineTerminator: '\n' })
}
@@ -0,0 +1,41 @@
module.exports = (file, api) => {
const jscodeshift = api.jscodeshift
const root = jscodeshift(file.source)
const baseRenameLogic = (kind, from, to) => {
root
.find(kind, (node) => {
return (
node.computed === false &&
(node.key?.name === from || node.key?.value === from)
)
})
.replaceWith(({ node: mutableNode }) => {
if (mutableNode.key.name !== undefined) {
mutableNode.key.name = to
}
if (mutableNode.key.value !== undefined) {
mutableNode.key.value = to
}
return mutableNode
})
}
const renameObjectProperty = (from, to) => {
baseRenameLogic(jscodeshift.ObjectProperty, from, to)
}
const renameTypeScriptPropertySignature = (from, to) => {
baseRenameLogic(jscodeshift.TSPropertySignature, from, to)
}
renameObjectProperty('cacheTime', 'gcTime')
renameObjectProperty('useErrorBoundary', 'throwOnError')
renameTypeScriptPropertySignature('cacheTime', 'gcTime')
renameTypeScriptPropertySignature('useErrorBoundary', 'throwOnError')
return root.toSource({ quote: 'single', lineTerminator: '\n' })
}
@@ -0,0 +1,82 @@
"use client";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_rolldown_runtime = require("./rolldown-runtime-VH7oDXx4.cjs");
const require_QueryClientProvider = require("./QueryClientProvider.cjs");
let react = require("react");
react = require_rolldown_runtime.__toESM(react, 1);
let _tanstack_query_core = require("@tanstack/query-core");
//#region src/HydrationBoundary.tsx
/**
* `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by
* `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on
* update timestamp.
*
* Note: Only `queries` can be dehydrated with an `HydrationBoundary`.
*
* @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the
* cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect
* after commit.
*
* @example
* ```tsx
* import { HydrationBoundary } from '@tanstack/react-query'
*
* function App() {
* return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>
* }
* ```
*
* @example
* Server-side prefetch handed off to the client via `dehydrate`:
* ```tsx
* import { HydrationBoundary, dehydrate, noop } from '@tanstack/react-query'
*
* async function ServerComponent() {
* const queryClient = getQueryClient()
*
* await queryClient
* .query({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* })
* .catch(noop)
*
* return (
* <HydrationBoundary state={dehydrate(queryClient)}>
* <Posts />
* </HydrationBoundary>
* )
* }
* ```
*/
const HydrationBoundary = ({ children, options = {}, state, queryClient }) => {
const client = require_QueryClientProvider.useQueryClient(queryClient);
const optionsRef = react.useRef(options);
react.useEffect(() => {
optionsRef.current = options;
});
const hydrationQueue = react.useMemo(() => {
if (state) {
if (typeof state !== "object") return;
const queryCache = client.getQueryCache();
const queries = state.queries || [];
const newQueries = [];
const existingQueries = [];
for (const dehydratedQuery of queries) {
const existingQuery = queryCache.get(dehydratedQuery.queryHash);
if (!existingQuery) newQueries.push(dehydratedQuery);
else if (dehydratedQuery.state.dataUpdatedAt > existingQuery.state.dataUpdatedAt || dehydratedQuery.promise && existingQuery.state.status !== "pending" && existingQuery.state.fetchStatus !== "fetching" && dehydratedQuery.dehydratedAt > existingQuery.state.dataUpdatedAt) existingQueries.push(dehydratedQuery);
}
if (newQueries.length > 0) (0, _tanstack_query_core.hydrate)(client, { queries: newQueries }, optionsRef.current);
if (existingQueries.length > 0) return existingQueries;
}
}, [client, state]);
react.useEffect(() => {
if (hydrationQueue) (0, _tanstack_query_core.hydrate)(client, { queries: hydrationQueue }, optionsRef.current);
}, [client, hydrationQueue]);
return children;
};
//#endregion
exports.HydrationBoundary = HydrationBoundary;
//# sourceMappingURL=HydrationBoundary.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"HydrationBoundary.cjs","names":["useQueryClient","React"],"sources":["../../src/HydrationBoundary.tsx"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nimport { hydrate } from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n DehydratedState,\n HydrateOptions,\n OmitKeyof,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * The props accepted by `HydrationBoundary`.\n */\nexport interface HydrationBoundaryProps {\n /**\n * The state to hydrate.\n */\n state: DehydratedState | null | undefined\n /**\n * Optional. Note: unlike `hydrate`, `mutations` cannot be set here.\n */\n options?: OmitKeyof<HydrateOptions, 'defaultOptions'> & {\n defaultOptions?: OmitKeyof<\n Exclude<HydrateOptions['defaultOptions'], undefined>,\n 'mutations'\n >\n }\n /**\n * The components to render — always rendered unconditionally, not gated on hydration. New queries are\n * hydrated into the cache during render; for queries that already exist in the cache, only newer dehydrated\n * data is hydrated, and that happens in an effect after commit, so `children` may render briefly before it\n * lands.\n */\n children?: React.ReactNode\n /**\n * Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used.\n */\n queryClient?: QueryClient\n}\n\n/**\n * `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by\n * `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on\n * update timestamp.\n *\n * Note: Only `queries` can be dehydrated with an `HydrationBoundary`.\n *\n * @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the\n * cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect\n * after commit.\n *\n * @example\n * ```tsx\n * import { HydrationBoundary } from '@tanstack/react-query'\n *\n * function App() {\n * return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>\n * }\n * ```\n *\n * @example\n * Server-side prefetch handed off to the client via `dehydrate`:\n * ```tsx\n * import { HydrationBoundary, dehydrate, noop } from '@tanstack/react-query'\n *\n * async function ServerComponent() {\n * const queryClient = getQueryClient()\n *\n * await queryClient\n * .query({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * })\n * .catch(noop)\n *\n * return (\n * <HydrationBoundary state={dehydrate(queryClient)}>\n * <Posts />\n * </HydrationBoundary>\n * )\n * }\n * ```\n */\nexport const HydrationBoundary = ({\n children,\n options = {},\n state,\n queryClient,\n}: HydrationBoundaryProps) => {\n const client = useQueryClient(queryClient)\n\n const optionsRef = React.useRef(options)\n React.useEffect(() => {\n optionsRef.current = options\n })\n\n // This useMemo is for performance reasons only, everything inside it must\n // be safe to run in every render and code here should be read as \"in render\".\n //\n // This code needs to happen during the render phase, because after initial\n // SSR, hydration needs to happen _before_ children render. Also, if hydrating\n // during a transition, we want to hydrate as much as is safe in render so\n // we can prerender as much as possible.\n //\n // For any queries that already exist in the cache, we want to hold back on\n // hydrating until _after_ the render phase. The reason for this is that during\n // transitions, we don't want the existing queries and observers to update to\n // the new data on the current page, only _after_ the transition is committed.\n // If the transition is aborted, we will have hydrated any _new_ queries, but\n // we throw away the fresh data for any existing ones to avoid unexpectedly\n // updating the UI.\n const hydrationQueue: DehydratedState['queries'] | undefined =\n React.useMemo(() => {\n if (state) {\n if (typeof state !== 'object') {\n return\n }\n\n const queryCache = client.getQueryCache()\n // State is supplied from the outside and we might as well fail\n // gracefully if it has the wrong shape, so while we type `queries`\n // as required, we still provide a fallback.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const queries = state.queries || []\n\n const newQueries: DehydratedState['queries'] = []\n const existingQueries: DehydratedState['queries'] = []\n for (const dehydratedQuery of queries) {\n const existingQuery = queryCache.get(dehydratedQuery.queryHash)\n\n if (!existingQuery) {\n newQueries.push(dehydratedQuery)\n } else {\n const hydrationIsNewer =\n dehydratedQuery.state.dataUpdatedALine truncated
@@ -0,0 +1,76 @@
import * as React from "react";
import { DehydratedState, HydrateOptions, OmitKeyof, QueryClient } from "@tanstack/query-core";
//#region src/HydrationBoundary.d.ts
/**
* The props accepted by `HydrationBoundary`.
*/
interface HydrationBoundaryProps {
/**
* The state to hydrate.
*/
state: DehydratedState | null | undefined;
/**
* Optional. Note: unlike `hydrate`, `mutations` cannot be set here.
*/
options?: OmitKeyof<HydrateOptions, 'defaultOptions'> & {
defaultOptions?: OmitKeyof<Exclude<HydrateOptions['defaultOptions'], undefined>, 'mutations'>;
};
/**
* The components to render — always rendered unconditionally, not gated on hydration. New queries are
* hydrated into the cache during render; for queries that already exist in the cache, only newer dehydrated
* data is hydrated, and that happens in an effect after commit, so `children` may render briefly before it
* lands.
*/
children?: React.ReactNode;
/**
* Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used.
*/
queryClient?: QueryClient;
}
/**
* `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by
* `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on
* update timestamp.
*
* Note: Only `queries` can be dehydrated with an `HydrationBoundary`.
*
* @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the
* cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect
* after commit.
*
* @example
* ```tsx
* import { HydrationBoundary } from '@tanstack/react-query'
*
* function App() {
* return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>
* }
* ```
*
* @example
* Server-side prefetch handed off to the client via `dehydrate`:
* ```tsx
* import { HydrationBoundary, dehydrate, noop } from '@tanstack/react-query'
*
* async function ServerComponent() {
* const queryClient = getQueryClient()
*
* await queryClient
* .query({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* })
* .catch(noop)
*
* return (
* <HydrationBoundary state={dehydrate(queryClient)}>
* <Posts />
* </HydrationBoundary>
* )
* }
* ```
*/
declare const HydrationBoundary: ({ children, options, state, queryClient }: HydrationBoundaryProps) => React.ReactElement;
//#endregion
export { HydrationBoundary, HydrationBoundaryProps };
//# sourceMappingURL=HydrationBoundary.d.cts.map
@@ -0,0 +1 @@
{"version":3,"file":"HydrationBoundary.d.cts","names":[],"sources":["../../src/HydrationBoundary.tsx"],"mappings":";;;;;;UAeiB;;;;EAIf,OAAO;;;;EAIP,UAAU,UAAU;IAClB,iBAAiB,UACf,QAAQ;;;;;;;;EAUZ,WAAW,MAAM;;;;EAIjB,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA8CH,sBAAqB,UAAA,SAAA,OAAA,eAK/B,2BA+EkB,MAAM"}
@@ -0,0 +1,76 @@
import * as React from "react";
import { DehydratedState, HydrateOptions, OmitKeyof, QueryClient } from "@tanstack/query-core";
//#region src/HydrationBoundary.d.ts
/**
* The props accepted by `HydrationBoundary`.
*/
interface HydrationBoundaryProps {
/**
* The state to hydrate.
*/
state: DehydratedState | null | undefined;
/**
* Optional. Note: unlike `hydrate`, `mutations` cannot be set here.
*/
options?: OmitKeyof<HydrateOptions, 'defaultOptions'> & {
defaultOptions?: OmitKeyof<Exclude<HydrateOptions['defaultOptions'], undefined>, 'mutations'>;
};
/**
* The components to render — always rendered unconditionally, not gated on hydration. New queries are
* hydrated into the cache during render; for queries that already exist in the cache, only newer dehydrated
* data is hydrated, and that happens in an effect after commit, so `children` may render briefly before it
* lands.
*/
children?: React.ReactNode;
/**
* Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used.
*/
queryClient?: QueryClient;
}
/**
* `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by
* `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on
* update timestamp.
*
* Note: Only `queries` can be dehydrated with an `HydrationBoundary`.
*
* @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the
* cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect
* after commit.
*
* @example
* ```tsx
* import { HydrationBoundary } from '@tanstack/react-query'
*
* function App() {
* return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>
* }
* ```
*
* @example
* Server-side prefetch handed off to the client via `dehydrate`:
* ```tsx
* import { HydrationBoundary, dehydrate, noop } from '@tanstack/react-query'
*
* async function ServerComponent() {
* const queryClient = getQueryClient()
*
* await queryClient
* .query({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* })
* .catch(noop)
*
* return (
* <HydrationBoundary state={dehydrate(queryClient)}>
* <Posts />
* </HydrationBoundary>
* )
* }
* ```
*/
declare const HydrationBoundary: ({ children, options, state, queryClient }: HydrationBoundaryProps) => React.ReactElement;
//#endregion
export { HydrationBoundary, HydrationBoundaryProps };
//# sourceMappingURL=HydrationBoundary.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"HydrationBoundary.d.ts","names":[],"sources":["../../src/HydrationBoundary.tsx"],"mappings":";;;;;;UAeiB;;;;EAIf,OAAO;;;;EAIP,UAAU,UAAU;IAClB,iBAAiB,UACf,QAAQ;;;;;;;;EAUZ,WAAW,MAAM;;;;EAIjB,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA8CH,sBAAqB,UAAA,SAAA,OAAA,eAK/B,2BA+EkB,MAAM"}
@@ -0,0 +1,79 @@
"use client";
import { useQueryClient } from "./QueryClientProvider.js";
import * as React from "react";
import { hydrate } from "@tanstack/query-core";
//#region src/HydrationBoundary.tsx
/**
* `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by
* `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on
* update timestamp.
*
* Note: Only `queries` can be dehydrated with an `HydrationBoundary`.
*
* @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the
* cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect
* after commit.
*
* @example
* ```tsx
* import { HydrationBoundary } from '@tanstack/react-query'
*
* function App() {
* return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>
* }
* ```
*
* @example
* Server-side prefetch handed off to the client via `dehydrate`:
* ```tsx
* import { HydrationBoundary, dehydrate, noop } from '@tanstack/react-query'
*
* async function ServerComponent() {
* const queryClient = getQueryClient()
*
* await queryClient
* .query({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* })
* .catch(noop)
*
* return (
* <HydrationBoundary state={dehydrate(queryClient)}>
* <Posts />
* </HydrationBoundary>
* )
* }
* ```
*/
const HydrationBoundary = ({ children, options = {}, state, queryClient }) => {
const client = useQueryClient(queryClient);
const optionsRef = React.useRef(options);
React.useEffect(() => {
optionsRef.current = options;
});
const hydrationQueue = React.useMemo(() => {
if (state) {
if (typeof state !== "object") return;
const queryCache = client.getQueryCache();
const queries = state.queries || [];
const newQueries = [];
const existingQueries = [];
for (const dehydratedQuery of queries) {
const existingQuery = queryCache.get(dehydratedQuery.queryHash);
if (!existingQuery) newQueries.push(dehydratedQuery);
else if (dehydratedQuery.state.dataUpdatedAt > existingQuery.state.dataUpdatedAt || dehydratedQuery.promise && existingQuery.state.status !== "pending" && existingQuery.state.fetchStatus !== "fetching" && dehydratedQuery.dehydratedAt > existingQuery.state.dataUpdatedAt) existingQueries.push(dehydratedQuery);
}
if (newQueries.length > 0) hydrate(client, { queries: newQueries }, optionsRef.current);
if (existingQueries.length > 0) return existingQueries;
}
}, [client, state]);
React.useEffect(() => {
if (hydrationQueue) hydrate(client, { queries: hydrationQueue }, optionsRef.current);
}, [client, hydrationQueue]);
return children;
};
//#endregion
export { HydrationBoundary };
//# sourceMappingURL=HydrationBoundary.js.map
@@ -0,0 +1 @@
{"version":3,"file":"HydrationBoundary.js","names":[],"sources":["../../src/HydrationBoundary.tsx"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nimport { hydrate } from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n DehydratedState,\n HydrateOptions,\n OmitKeyof,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * The props accepted by `HydrationBoundary`.\n */\nexport interface HydrationBoundaryProps {\n /**\n * The state to hydrate.\n */\n state: DehydratedState | null | undefined\n /**\n * Optional. Note: unlike `hydrate`, `mutations` cannot be set here.\n */\n options?: OmitKeyof<HydrateOptions, 'defaultOptions'> & {\n defaultOptions?: OmitKeyof<\n Exclude<HydrateOptions['defaultOptions'], undefined>,\n 'mutations'\n >\n }\n /**\n * The components to render — always rendered unconditionally, not gated on hydration. New queries are\n * hydrated into the cache during render; for queries that already exist in the cache, only newer dehydrated\n * data is hydrated, and that happens in an effect after commit, so `children` may render briefly before it\n * lands.\n */\n children?: React.ReactNode\n /**\n * Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used.\n */\n queryClient?: QueryClient\n}\n\n/**\n * `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by\n * `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on\n * update timestamp.\n *\n * Note: Only `queries` can be dehydrated with an `HydrationBoundary`.\n *\n * @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the\n * cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect\n * after commit.\n *\n * @example\n * ```tsx\n * import { HydrationBoundary } from '@tanstack/react-query'\n *\n * function App() {\n * return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>\n * }\n * ```\n *\n * @example\n * Server-side prefetch handed off to the client via `dehydrate`:\n * ```tsx\n * import { HydrationBoundary, dehydrate, noop } from '@tanstack/react-query'\n *\n * async function ServerComponent() {\n * const queryClient = getQueryClient()\n *\n * await queryClient\n * .query({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * })\n * .catch(noop)\n *\n * return (\n * <HydrationBoundary state={dehydrate(queryClient)}>\n * <Posts />\n * </HydrationBoundary>\n * )\n * }\n * ```\n */\nexport const HydrationBoundary = ({\n children,\n options = {},\n state,\n queryClient,\n}: HydrationBoundaryProps) => {\n const client = useQueryClient(queryClient)\n\n const optionsRef = React.useRef(options)\n React.useEffect(() => {\n optionsRef.current = options\n })\n\n // This useMemo is for performance reasons only, everything inside it must\n // be safe to run in every render and code here should be read as \"in render\".\n //\n // This code needs to happen during the render phase, because after initial\n // SSR, hydration needs to happen _before_ children render. Also, if hydrating\n // during a transition, we want to hydrate as much as is safe in render so\n // we can prerender as much as possible.\n //\n // For any queries that already exist in the cache, we want to hold back on\n // hydrating until _after_ the render phase. The reason for this is that during\n // transitions, we don't want the existing queries and observers to update to\n // the new data on the current page, only _after_ the transition is committed.\n // If the transition is aborted, we will have hydrated any _new_ queries, but\n // we throw away the fresh data for any existing ones to avoid unexpectedly\n // updating the UI.\n const hydrationQueue: DehydratedState['queries'] | undefined =\n React.useMemo(() => {\n if (state) {\n if (typeof state !== 'object') {\n return\n }\n\n const queryCache = client.getQueryCache()\n // State is supplied from the outside and we might as well fail\n // gracefully if it has the wrong shape, so while we type `queries`\n // as required, we still provide a fallback.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const queries = state.queries || []\n\n const newQueries: DehydratedState['queries'] = []\n const existingQueries: DehydratedState['queries'] = []\n for (const dehydratedQuery of queries) {\n const existingQuery = queryCache.get(dehydratedQuery.queryHash)\n\n if (!existingQuery) {\n newQueries.push(dehydratedQuery)\n } else {\n const hydrationIsNewer =\n dehydratedQuery.state.dataUpdatedAt >\n exisLine truncated
@@ -0,0 +1,25 @@
"use client";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_rolldown_runtime = require("./rolldown-runtime-VH7oDXx4.cjs");
let react = require("react");
react = require_rolldown_runtime.__toESM(react, 1);
//#region src/IsRestoringProvider.ts
const IsRestoringContext = react.createContext(false);
/**
* If you are using `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.
*
* @returns `true` while a persisted client is being restored, `false` otherwise.
*/
const useIsRestoring = () => react.useContext(IsRestoringContext);
/**
* The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently
* being restored, read by `useIsRestoring`.
*/
const IsRestoringProvider = IsRestoringContext.Provider;
//#endregion
exports.IsRestoringProvider = IsRestoringProvider;
exports.useIsRestoring = useIsRestoring;
//# sourceMappingURL=IsRestoringProvider.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"IsRestoringProvider.cjs","names":["React"],"sources":["../../src/IsRestoringProvider.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nconst IsRestoringContext = React.createContext(false)\n\n/**\n * If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to\n * check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid\n * race conditions between the restore and mounting queries.\n *\n * @returns `true` while a persisted client is being restored, `false` otherwise.\n */\nexport const useIsRestoring = () => React.useContext(IsRestoringContext)\n\n/**\n * The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently\n * being restored, read by `useIsRestoring`.\n */\nexport const IsRestoringProvider = IsRestoringContext.Provider\n"],"mappings":";;;;;;AAGA,MAAM,qBAAqBA,MAAM,cAAc,KAAK;;;;;;;;AASpD,MAAa,uBAAuBA,MAAM,WAAW,kBAAkB;;;;;AAMvE,MAAa,sBAAsB,mBAAmB"}
@@ -0,0 +1,18 @@
import * as React from "react";
//#region src/IsRestoringProvider.d.ts
/**
* If you are using `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.
*
* @returns `true` while a persisted client is being restored, `false` otherwise.
*/
declare const useIsRestoring: () => boolean;
/**
* The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently
* being restored, read by `useIsRestoring`.
*/
declare const IsRestoringProvider: React.Provider<boolean>;
//#endregion
export { IsRestoringProvider, useIsRestoring };
//# sourceMappingURL=IsRestoringProvider.d.cts.map
@@ -0,0 +1 @@
{"version":3,"file":"IsRestoringProvider.d.cts","names":[],"sources":["../../src/IsRestoringProvider.ts"],"mappings":";;;;;;;;;cAYa;;;;;cAMA,qBAAmB,MAAA"}
@@ -0,0 +1,18 @@
import * as React from "react";
//#region src/IsRestoringProvider.d.ts
/**
* If you are using `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.
*
* @returns `true` while a persisted client is being restored, `false` otherwise.
*/
declare const useIsRestoring: () => boolean;
/**
* The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently
* being restored, read by `useIsRestoring`.
*/
declare const IsRestoringProvider: React.Provider<boolean>;
//#endregion
export { IsRestoringProvider, useIsRestoring };
//# sourceMappingURL=IsRestoringProvider.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"IsRestoringProvider.d.ts","names":[],"sources":["../../src/IsRestoringProvider.ts"],"mappings":";;;;;;;;;cAYa;;;;;cAMA,qBAAmB,MAAA"}
@@ -0,0 +1,21 @@
"use client";
import * as React from "react";
//#region src/IsRestoringProvider.ts
const IsRestoringContext = React.createContext(false);
/**
* If you are using `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.
*
* @returns `true` while a persisted client is being restored, `false` otherwise.
*/
const useIsRestoring = () => React.useContext(IsRestoringContext);
/**
* The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently
* being restored, read by `useIsRestoring`.
*/
const IsRestoringProvider = IsRestoringContext.Provider;
//#endregion
export { IsRestoringProvider, useIsRestoring };
//# sourceMappingURL=IsRestoringProvider.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IsRestoringProvider.js","names":[],"sources":["../../src/IsRestoringProvider.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nconst IsRestoringContext = React.createContext(false)\n\n/**\n * If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to\n * check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid\n * race conditions between the restore and mounting queries.\n *\n * @returns `true` while a persisted client is being restored, `false` otherwise.\n */\nexport const useIsRestoring = () => React.useContext(IsRestoringContext)\n\n/**\n * The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently\n * being restored, read by `useIsRestoring`.\n */\nexport const IsRestoringProvider = IsRestoringContext.Provider\n"],"mappings":";;;AAGA,MAAM,qBAAqB,MAAM,cAAc,KAAK;;;;;;;;AASpD,MAAa,uBAAuB,MAAM,WAAW,kBAAkB;;;;;AAMvE,MAAa,sBAAsB,mBAAmB"}
@@ -0,0 +1,62 @@
"use client";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_rolldown_runtime = require("./rolldown-runtime-VH7oDXx4.cjs");
let react = require("react");
react = require_rolldown_runtime.__toESM(react, 1);
let react_jsx_runtime = require("react/jsx-runtime");
//#region src/QueryClientProvider.tsx
/**
* The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it.
*/
const QueryClientContext = react.createContext(void 0);
/**
* The `useQueryClient` hook returns the current `QueryClient` instance.
*
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns The current `QueryClient` instance.
* @throws If no `queryClient` argument is passed and no `QueryClientProvider` is found in the component tree.
*/
const useQueryClient = (queryClient) => {
const client = react.useContext(QueryClientContext);
if (queryClient) return queryClient;
if (!client) throw new Error("No QueryClient set, use QueryClientProvider to set one");
return client;
};
/**
* Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also
* calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to
* focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or
* comes back online).
*
* @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`.
*
* @example
* ```tsx
* import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
*
* const queryClient = new QueryClient()
*
* function App() {
* return <QueryClientProvider client={queryClient}>...</QueryClientProvider>
* }
* ```
*/
const QueryClientProvider = ({ client, children }) => {
react.useEffect(() => {
client.mount();
return () => {
client.unmount();
};
}, [client]);
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(QueryClientContext.Provider, {
value: client,
children
});
};
//#endregion
exports.QueryClientContext = QueryClientContext;
exports.QueryClientProvider = QueryClientProvider;
exports.useQueryClient = useQueryClient;
//# sourceMappingURL=QueryClientProvider.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"QueryClientProvider.cjs","names":["React"],"sources":["../../src/QueryClientProvider.tsx"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nimport type { QueryClient } from '@tanstack/query-core'\n\n/**\n * The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it.\n */\nexport const QueryClientContext = React.createContext<QueryClient | undefined>(\n undefined,\n)\n\n/**\n * The `useQueryClient` hook returns the current `QueryClient` instance.\n *\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns The current `QueryClient` instance.\n * @throws If no `queryClient` argument is passed and no `QueryClientProvider` is found in the component tree.\n */\nexport const useQueryClient = (queryClient?: QueryClient) => {\n const client = React.useContext(QueryClientContext)\n\n if (queryClient) {\n return queryClient\n }\n\n if (!client) {\n throw new Error('No QueryClient set, use QueryClientProvider to set one')\n }\n\n return client\n}\n\n/**\n * The props accepted by `QueryClientProvider`.\n */\nexport type QueryClientProviderProps = {\n /**\n * **Required**\n *\n * The `QueryClient` instance to provide.\n */\n client: QueryClient\n /**\n * The components that get access to the provided `QueryClient`.\n */\n children?: React.ReactNode\n}\n\n/**\n * Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also\n * calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to\n * focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or\n * comes back online).\n *\n * @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`.\n *\n * @example\n * ```tsx\n * import { QueryClient, QueryClientProvider } from '@tanstack/react-query'\n *\n * const queryClient = new QueryClient()\n *\n * function App() {\n * return <QueryClientProvider client={queryClient}>...</QueryClientProvider>\n * }\n * ```\n */\nexport const QueryClientProvider = ({\n client,\n children,\n}: QueryClientProviderProps): React.JSX.Element => {\n React.useEffect(() => {\n client.mount()\n return () => {\n client.unmount()\n }\n }, [client])\n\n return (\n <QueryClientContext.Provider value={client}>\n {children}\n </QueryClientContext.Provider>\n )\n}\n"],"mappings":";;;;;;;;;;AAQA,MAAa,qBAAqBA,MAAM,cACtC,KAAA,CACF;;;;;;;;;AAUA,MAAa,kBAAkB,gBAA8B;CAC3D,MAAM,SAASA,MAAM,WAAW,kBAAkB;CAElD,IAAI,aACF,OAAO;CAGT,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,wDAAwD;CAG1E,OAAO;AACT;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,uBAAuB,EAClC,QACA,eACiD;CACjD,MAAM,gBAAgB;EACpB,OAAO,MAAM;EACb,aAAa;GACX,OAAO,QAAQ;EACjB;CACF,GAAG,CAAC,MAAM,CAAC;CAEX,OACE,iBAAA,GAAA,kBAAA,IAAA,CAAC,mBAAmB,UAApB;EAA6B,OAAO;EACjC;CAC0B,CAAA;AAEjC"}
@@ -0,0 +1,54 @@
import * as React from "react";
import { QueryClient } from "@tanstack/query-core";
//#region src/QueryClientProvider.d.ts
/**
* The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it.
*/
declare const QueryClientContext: React.Context<QueryClient | undefined>;
/**
* The `useQueryClient` hook returns the current `QueryClient` instance.
*
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns The current `QueryClient` instance.
* @throws If no `queryClient` argument is passed and no `QueryClientProvider` is found in the component tree.
*/
declare const useQueryClient: (queryClient?: QueryClient) => QueryClient;
/**
* The props accepted by `QueryClientProvider`.
*/
type QueryClientProviderProps = {
/**
* **Required**
*
* The `QueryClient` instance to provide.
*/
client: QueryClient;
/**
* The components that get access to the provided `QueryClient`.
*/
children?: React.ReactNode;
};
/**
* Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also
* calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to
* focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or
* comes back online).
*
* @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`.
*
* @example
* ```tsx
* import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
*
* const queryClient = new QueryClient()
*
* function App() {
* return <QueryClientProvider client={queryClient}>...</QueryClientProvider>
* }
* ```
*/
declare const QueryClientProvider: ({ client, children }: QueryClientProviderProps) => React.JSX.Element;
//#endregion
export { QueryClientContext, QueryClientProvider, QueryClientProviderProps, useQueryClient };
//# sourceMappingURL=QueryClientProvider.d.cts.map
@@ -0,0 +1 @@
{"version":3,"file":"QueryClientProvider.d.cts","names":[],"sources":["../../src/QueryClientProvider.tsx"],"mappings":";;;;;;cAQa,oBAAkB,MAAA,QAAA;;;;;;;;;cAYlB,iBAAkB,cAAc,gBAAW;;;;KAiB5C;;;;;;EAMV,QAAQ;;;;EAIR,WAAW,MAAM;;;;;;;;;;;;;;;;;;;;;cAsBN,wBAAuB,QAAA,YAGjC,6BAA2B,MAAM,IAAI"}
@@ -0,0 +1,54 @@
import * as React from "react";
import { QueryClient } from "@tanstack/query-core";
//#region src/QueryClientProvider.d.ts
/**
* The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it.
*/
declare const QueryClientContext: React.Context<QueryClient | undefined>;
/**
* The `useQueryClient` hook returns the current `QueryClient` instance.
*
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns The current `QueryClient` instance.
* @throws If no `queryClient` argument is passed and no `QueryClientProvider` is found in the component tree.
*/
declare const useQueryClient: (queryClient?: QueryClient) => QueryClient;
/**
* The props accepted by `QueryClientProvider`.
*/
type QueryClientProviderProps = {
/**
* **Required**
*
* The `QueryClient` instance to provide.
*/
client: QueryClient;
/**
* The components that get access to the provided `QueryClient`.
*/
children?: React.ReactNode;
};
/**
* Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also
* calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to
* focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or
* comes back online).
*
* @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`.
*
* @example
* ```tsx
* import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
*
* const queryClient = new QueryClient()
*
* function App() {
* return <QueryClientProvider client={queryClient}>...</QueryClientProvider>
* }
* ```
*/
declare const QueryClientProvider: ({ client, children }: QueryClientProviderProps) => React.JSX.Element;
//#endregion
export { QueryClientContext, QueryClientProvider, QueryClientProviderProps, useQueryClient };
//# sourceMappingURL=QueryClientProvider.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"QueryClientProvider.d.ts","names":[],"sources":["../../src/QueryClientProvider.tsx"],"mappings":";;;;;;cAQa,oBAAkB,MAAA,QAAA;;;;;;;;;cAYlB,iBAAkB,cAAc,gBAAW;;;;KAiB5C;;;;;;EAMV,QAAQ;;;;EAIR,WAAW,MAAM;;;;;;;;;;;;;;;;;;;;;cAsBN,wBAAuB,QAAA,YAGjC,6BAA2B,MAAM,IAAI"}
@@ -0,0 +1,57 @@
"use client";
import * as React from "react";
import { jsx } from "react/jsx-runtime";
//#region src/QueryClientProvider.tsx
/**
* The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it.
*/
const QueryClientContext = React.createContext(void 0);
/**
* The `useQueryClient` hook returns the current `QueryClient` instance.
*
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns The current `QueryClient` instance.
* @throws If no `queryClient` argument is passed and no `QueryClientProvider` is found in the component tree.
*/
const useQueryClient = (queryClient) => {
const client = React.useContext(QueryClientContext);
if (queryClient) return queryClient;
if (!client) throw new Error("No QueryClient set, use QueryClientProvider to set one");
return client;
};
/**
* Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also
* calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to
* focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or
* comes back online).
*
* @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`.
*
* @example
* ```tsx
* import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
*
* const queryClient = new QueryClient()
*
* function App() {
* return <QueryClientProvider client={queryClient}>...</QueryClientProvider>
* }
* ```
*/
const QueryClientProvider = ({ client, children }) => {
React.useEffect(() => {
client.mount();
return () => {
client.unmount();
};
}, [client]);
return /* @__PURE__ */ jsx(QueryClientContext.Provider, {
value: client,
children
});
};
//#endregion
export { QueryClientContext, QueryClientProvider, useQueryClient };
//# sourceMappingURL=QueryClientProvider.js.map
@@ -0,0 +1 @@
{"version":3,"file":"QueryClientProvider.js","names":[],"sources":["../../src/QueryClientProvider.tsx"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nimport type { QueryClient } from '@tanstack/query-core'\n\n/**\n * The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it.\n */\nexport const QueryClientContext = React.createContext<QueryClient | undefined>(\n undefined,\n)\n\n/**\n * The `useQueryClient` hook returns the current `QueryClient` instance.\n *\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns The current `QueryClient` instance.\n * @throws If no `queryClient` argument is passed and no `QueryClientProvider` is found in the component tree.\n */\nexport const useQueryClient = (queryClient?: QueryClient) => {\n const client = React.useContext(QueryClientContext)\n\n if (queryClient) {\n return queryClient\n }\n\n if (!client) {\n throw new Error('No QueryClient set, use QueryClientProvider to set one')\n }\n\n return client\n}\n\n/**\n * The props accepted by `QueryClientProvider`.\n */\nexport type QueryClientProviderProps = {\n /**\n * **Required**\n *\n * The `QueryClient` instance to provide.\n */\n client: QueryClient\n /**\n * The components that get access to the provided `QueryClient`.\n */\n children?: React.ReactNode\n}\n\n/**\n * Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also\n * calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to\n * focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or\n * comes back online).\n *\n * @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`.\n *\n * @example\n * ```tsx\n * import { QueryClient, QueryClientProvider } from '@tanstack/react-query'\n *\n * const queryClient = new QueryClient()\n *\n * function App() {\n * return <QueryClientProvider client={queryClient}>...</QueryClientProvider>\n * }\n * ```\n */\nexport const QueryClientProvider = ({\n client,\n children,\n}: QueryClientProviderProps): React.JSX.Element => {\n React.useEffect(() => {\n client.mount()\n return () => {\n client.unmount()\n }\n }, [client])\n\n return (\n <QueryClientContext.Provider value={client}>\n {children}\n </QueryClientContext.Provider>\n )\n}\n"],"mappings":";;;;;;;AAQA,MAAa,qBAAqB,MAAM,cACtC,KAAA,CACF;;;;;;;;;AAUA,MAAa,kBAAkB,gBAA8B;CAC3D,MAAM,SAAS,MAAM,WAAW,kBAAkB;CAElD,IAAI,aACF,OAAO;CAGT,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,wDAAwD;CAG1E,OAAO;AACT;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,uBAAuB,EAClC,QACA,eACiD;CACjD,MAAM,gBAAgB;EACpB,OAAO,MAAM;EACb,aAAa;GACX,OAAO,QAAQ;EACjB;CACF,GAAG,CAAC,MAAM,CAAC;CAEX,OACE,oBAAC,mBAAmB,UAApB;EAA6B,OAAO;EACjC;CAC0B,CAAA;AAEjC"}
@@ -0,0 +1,111 @@
"use client";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_rolldown_runtime = require("./rolldown-runtime-VH7oDXx4.cjs");
let react = require("react");
react = require_rolldown_runtime.__toESM(react, 1);
let react_jsx_runtime = require("react/jsx-runtime");
//#region src/QueryErrorResetBoundary.tsx
/**
* Resets any query errors within the boundary, so queries know they can try again.
*/
function createValue() {
let isReset = false;
return {
/**
* Clears the reset state, so queries know not to try again until the boundary is reset again.
*/
clearReset: () => {
isReset = false;
},
/**
* Resets any query errors within the boundary, so queries know they can try again.
*/
reset: () => {
isReset = true;
},
/**
* Returns whether the boundary has been reset and not yet cleared.
*/
isReset: () => {
return isReset;
}
};
}
const QueryErrorResetBoundaryContext = react.createContext(createValue());
/**
* This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary
* defined it will reset them globally.
*
* @returns The boundary's {@link QueryErrorResetBoundaryValue}.
*
* @example
* ```tsx
* import { ErrorBoundary } from 'react-error-boundary'
* import { useQueryErrorResetBoundary } from '@tanstack/react-query'
*
* function App({ children }: { children: React.ReactNode }) {
* const { reset } = useQueryErrorResetBoundary()
*
* return (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* {children}
* </ErrorBoundary>
* )
* }
* ```
*/
const useQueryErrorResetBoundary = () => react.useContext(QueryErrorResetBoundaryContext);
/**
* When using `suspense` or `throwOnError` in your queries, you need a way to let queries know that you want to
* try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can
* reset any query errors within the boundaries of the component.
*
* @returns The `children`, rendered as-is, or called with the boundary's {@link QueryErrorResetBoundaryValue}
* if `children` is a function.
*
* @example
* ```tsx
* import { ErrorBoundary } from 'react-error-boundary'
* import { QueryErrorResetBoundary } from '@tanstack/react-query'
*
* function App() {
* return (
* <QueryErrorResetBoundary>
* {({ reset }) => (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* <Page />
* </ErrorBoundary>
* )}
* </QueryErrorResetBoundary>
* )
* }
* ```
*/
const QueryErrorResetBoundary = ({ children }) => {
const [value] = react.useState(() => createValue());
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(QueryErrorResetBoundaryContext.Provider, {
value,
children: typeof children === "function" ? children(value) : children
});
};
//#endregion
exports.QueryErrorResetBoundary = QueryErrorResetBoundary;
exports.useQueryErrorResetBoundary = useQueryErrorResetBoundary;
//# sourceMappingURL=QueryErrorResetBoundary.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"QueryErrorResetBoundary.cjs","names":["React"],"sources":["../../src/QueryErrorResetBoundary.tsx"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\n// CONTEXT\nexport type QueryErrorResetFunction = () => void\nexport type QueryErrorIsResetFunction = () => boolean\nexport type QueryErrorClearResetFunction = () => void\n\nexport interface QueryErrorResetBoundaryValue {\n clearReset: QueryErrorClearResetFunction\n isReset: QueryErrorIsResetFunction\n reset: QueryErrorResetFunction\n}\n\n/**\n * Resets any query errors within the boundary, so queries know they can try again.\n */\nfunction createValue(): QueryErrorResetBoundaryValue {\n let isReset = false\n return {\n /**\n * Clears the reset state, so queries know not to try again until the boundary is reset again.\n */\n clearReset: () => {\n isReset = false\n },\n /**\n * Resets any query errors within the boundary, so queries know they can try again.\n */\n reset: () => {\n isReset = true\n },\n /**\n * Returns whether the boundary has been reset and not yet cleared.\n */\n isReset: () => {\n return isReset\n },\n }\n}\n\nconst QueryErrorResetBoundaryContext = React.createContext(createValue())\n\n// HOOK\n\n/**\n * This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary\n * defined it will reset them globally.\n *\n * @returns The boundary's {@link QueryErrorResetBoundaryValue}.\n *\n * @example\n * ```tsx\n * import { ErrorBoundary } from 'react-error-boundary'\n * import { useQueryErrorResetBoundary } from '@tanstack/react-query'\n *\n * function App({ children }: { children: React.ReactNode }) {\n * const { reset } = useQueryErrorResetBoundary()\n *\n * return (\n * <ErrorBoundary\n * onReset={reset}\n * fallbackRender={({ resetErrorBoundary }) => (\n * <div>\n * There was an error!\n * <button onClick={() => resetErrorBoundary()}>Try again</button>\n * </div>\n * )}\n * >\n * {children}\n * </ErrorBoundary>\n * )\n * }\n * ```\n */\nexport const useQueryErrorResetBoundary = () =>\n React.useContext(QueryErrorResetBoundaryContext)\n\n// COMPONENT\n\n/**\n * A render-prop function usable as `children` on `QueryErrorResetBoundary`.\n *\n * @param value - The boundary's {@link QueryErrorResetBoundaryValue}.\n * @returns The children to render.\n */\nexport type QueryErrorResetBoundaryFunction = (\n value: QueryErrorResetBoundaryValue,\n) => React.ReactNode\n\n/**\n * The props accepted by `QueryErrorResetBoundary`.\n */\nexport interface QueryErrorResetBoundaryProps {\n /**\n * Either a plain node, or a function that receives the boundary's {@link QueryErrorResetBoundaryValue} and\n * returns a node.\n */\n children: QueryErrorResetBoundaryFunction | React.ReactNode\n}\n\n/**\n * When using `suspense` or `throwOnError` in your queries, you need a way to let queries know that you want to\n * try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can\n * reset any query errors within the boundaries of the component.\n *\n * @returns The `children`, rendered as-is, or called with the boundary's {@link QueryErrorResetBoundaryValue}\n * if `children` is a function.\n *\n * @example\n * ```tsx\n * import { ErrorBoundary } from 'react-error-boundary'\n * import { QueryErrorResetBoundary } from '@tanstack/react-query'\n *\n * function App() {\n * return (\n * <QueryErrorResetBoundary>\n * {({ reset }) => (\n * <ErrorBoundary\n * onReset={reset}\n * fallbackRender={({ resetErrorBoundary }) => (\n * <div>\n * There was an error!\n * <button onClick={() => resetErrorBoundary()}>Try again</button>\n * </div>\n * )}\n * >\n * <Page />\n * </ErrorBoundary>\n * )}\n * </QueryErrorResetBoundary>\n * )\n * }\n * ```\n */\nexport const QueryErrorResetBoundary = ({\n children,\n}: QueryErrorResetBoundaryProps) => {\n const [value] = React.useState(() => createValue())\n return (\n <QueryErrorResetBoundaryContext.Provider value={value}>\n {typeof children === 'function' ? children(value) : children}\n </QueryErrorResetBoundaryContext.Provider>\n )\n}\n"],"mappings":";;;;;;;;;;AAiBA,SAAS,cAA4C;CACnD,IAAI,UAAU;CACd,OAAO;;;;EAIL,kBAAkB;GAChB,UAAU;EACZ;;;;EAIA,aAAa;GACX,UAAU;EACZ;;;;EAIA,eAAe;GACb,OAAO;EACT;CACF;AACF;AAEA,MAAM,iCAAiCA,MAAM,cAAc,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCxE,MAAa,mCACXA,MAAM,WAAW,8BAA8B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DjD,MAAa,2BAA2B,EACtC,eACkC;CAClC,MAAM,CAAC,SAASA,MAAM,eAAe,YAAY,CAAC;CAClD,OACE,iBAAA,GAAA,kBAAA,IAAA,CAAC,+BAA+B,UAAhC;EAAgD;EAC7C,UAAA,OAAO,aAAa,aAAa,SAAS,KAAK,IAAI;CACb,CAAA;AAE7C"}
@@ -0,0 +1,96 @@
import * as React from "react";
//#region src/QueryErrorResetBoundary.d.ts
type QueryErrorResetFunction = () => void;
type QueryErrorIsResetFunction = () => boolean;
type QueryErrorClearResetFunction = () => void;
interface QueryErrorResetBoundaryValue {
clearReset: QueryErrorClearResetFunction;
isReset: QueryErrorIsResetFunction;
reset: QueryErrorResetFunction;
}
/**
* This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary
* defined it will reset them globally.
*
* @returns The boundary's {@link QueryErrorResetBoundaryValue}.
*
* @example
* ```tsx
* import { ErrorBoundary } from 'react-error-boundary'
* import { useQueryErrorResetBoundary } from '@tanstack/react-query'
*
* function App({ children }: { children: React.ReactNode }) {
* const { reset } = useQueryErrorResetBoundary()
*
* return (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* {children}
* </ErrorBoundary>
* )
* }
* ```
*/
declare const useQueryErrorResetBoundary: () => QueryErrorResetBoundaryValue;
/**
* A render-prop function usable as `children` on `QueryErrorResetBoundary`.
*
* @param value - The boundary's {@link QueryErrorResetBoundaryValue}.
* @returns The children to render.
*/
type QueryErrorResetBoundaryFunction = (value: QueryErrorResetBoundaryValue) => React.ReactNode;
/**
* The props accepted by `QueryErrorResetBoundary`.
*/
interface QueryErrorResetBoundaryProps {
/**
* Either a plain node, or a function that receives the boundary's {@link QueryErrorResetBoundaryValue} and
* returns a node.
*/
children: QueryErrorResetBoundaryFunction | React.ReactNode;
}
/**
* When using `suspense` or `throwOnError` in your queries, you need a way to let queries know that you want to
* try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can
* reset any query errors within the boundaries of the component.
*
* @returns The `children`, rendered as-is, or called with the boundary's {@link QueryErrorResetBoundaryValue}
* if `children` is a function.
*
* @example
* ```tsx
* import { ErrorBoundary } from 'react-error-boundary'
* import { QueryErrorResetBoundary } from '@tanstack/react-query'
*
* function App() {
* return (
* <QueryErrorResetBoundary>
* {({ reset }) => (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* <Page />
* </ErrorBoundary>
* )}
* </QueryErrorResetBoundary>
* )
* }
* ```
*/
declare const QueryErrorResetBoundary: ({ children }: QueryErrorResetBoundaryProps) => import("react/jsx-runtime").JSX.Element;
//#endregion
export { QueryErrorClearResetFunction, QueryErrorIsResetFunction, QueryErrorResetBoundary, QueryErrorResetBoundaryFunction, QueryErrorResetBoundaryProps, QueryErrorResetBoundaryValue, QueryErrorResetFunction, useQueryErrorResetBoundary };
//# sourceMappingURL=QueryErrorResetBoundary.d.cts.map
@@ -0,0 +1 @@
{"version":3,"file":"QueryErrorResetBoundary.d.cts","names":[],"sources":["../../src/QueryErrorResetBoundary.tsx"],"mappings":";;KAIY;KACA;KACA;UAEK;EACf,YAAY;EACZ,SAAS;EACT,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAgEI,kCAA0B;;;;;;;KAW3B,mCACV,OAAO,iCACJ,MAAM;;;;UAKM;;;;;EAKf,UAAU,kCAAkC,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAqCvC,4BAA2B,YAErC,6DAA4B,IAAA"}
@@ -0,0 +1,96 @@
import * as React from "react";
//#region src/QueryErrorResetBoundary.d.ts
type QueryErrorResetFunction = () => void;
type QueryErrorIsResetFunction = () => boolean;
type QueryErrorClearResetFunction = () => void;
interface QueryErrorResetBoundaryValue {
clearReset: QueryErrorClearResetFunction;
isReset: QueryErrorIsResetFunction;
reset: QueryErrorResetFunction;
}
/**
* This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary
* defined it will reset them globally.
*
* @returns The boundary's {@link QueryErrorResetBoundaryValue}.
*
* @example
* ```tsx
* import { ErrorBoundary } from 'react-error-boundary'
* import { useQueryErrorResetBoundary } from '@tanstack/react-query'
*
* function App({ children }: { children: React.ReactNode }) {
* const { reset } = useQueryErrorResetBoundary()
*
* return (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* {children}
* </ErrorBoundary>
* )
* }
* ```
*/
declare const useQueryErrorResetBoundary: () => QueryErrorResetBoundaryValue;
/**
* A render-prop function usable as `children` on `QueryErrorResetBoundary`.
*
* @param value - The boundary's {@link QueryErrorResetBoundaryValue}.
* @returns The children to render.
*/
type QueryErrorResetBoundaryFunction = (value: QueryErrorResetBoundaryValue) => React.ReactNode;
/**
* The props accepted by `QueryErrorResetBoundary`.
*/
interface QueryErrorResetBoundaryProps {
/**
* Either a plain node, or a function that receives the boundary's {@link QueryErrorResetBoundaryValue} and
* returns a node.
*/
children: QueryErrorResetBoundaryFunction | React.ReactNode;
}
/**
* When using `suspense` or `throwOnError` in your queries, you need a way to let queries know that you want to
* try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can
* reset any query errors within the boundaries of the component.
*
* @returns The `children`, rendered as-is, or called with the boundary's {@link QueryErrorResetBoundaryValue}
* if `children` is a function.
*
* @example
* ```tsx
* import { ErrorBoundary } from 'react-error-boundary'
* import { QueryErrorResetBoundary } from '@tanstack/react-query'
*
* function App() {
* return (
* <QueryErrorResetBoundary>
* {({ reset }) => (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* <Page />
* </ErrorBoundary>
* )}
* </QueryErrorResetBoundary>
* )
* }
* ```
*/
declare const QueryErrorResetBoundary: ({ children }: QueryErrorResetBoundaryProps) => import("react/jsx-runtime").JSX.Element;
//#endregion
export { QueryErrorClearResetFunction, QueryErrorIsResetFunction, QueryErrorResetBoundary, QueryErrorResetBoundaryFunction, QueryErrorResetBoundaryProps, QueryErrorResetBoundaryValue, QueryErrorResetFunction, useQueryErrorResetBoundary };
//# sourceMappingURL=QueryErrorResetBoundary.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"QueryErrorResetBoundary.d.ts","names":[],"sources":["../../src/QueryErrorResetBoundary.tsx"],"mappings":";;KAIY;KACA;KACA;UAEK;EACf,YAAY;EACZ,SAAS;EACT,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAgEI,kCAA0B;;;;;;;KAW3B,mCACV,OAAO,iCACJ,MAAM;;;;UAKM;;;;;EAKf,UAAU,kCAAkC,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAqCvC,4BAA2B,YAErC,6DAA4B,IAAA"}
@@ -0,0 +1,107 @@
"use client";
import * as React from "react";
import { jsx } from "react/jsx-runtime";
//#region src/QueryErrorResetBoundary.tsx
/**
* Resets any query errors within the boundary, so queries know they can try again.
*/
function createValue() {
let isReset = false;
return {
/**
* Clears the reset state, so queries know not to try again until the boundary is reset again.
*/
clearReset: () => {
isReset = false;
},
/**
* Resets any query errors within the boundary, so queries know they can try again.
*/
reset: () => {
isReset = true;
},
/**
* Returns whether the boundary has been reset and not yet cleared.
*/
isReset: () => {
return isReset;
}
};
}
const QueryErrorResetBoundaryContext = React.createContext(createValue());
/**
* This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary
* defined it will reset them globally.
*
* @returns The boundary's {@link QueryErrorResetBoundaryValue}.
*
* @example
* ```tsx
* import { ErrorBoundary } from 'react-error-boundary'
* import { useQueryErrorResetBoundary } from '@tanstack/react-query'
*
* function App({ children }: { children: React.ReactNode }) {
* const { reset } = useQueryErrorResetBoundary()
*
* return (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* {children}
* </ErrorBoundary>
* )
* }
* ```
*/
const useQueryErrorResetBoundary = () => React.useContext(QueryErrorResetBoundaryContext);
/**
* When using `suspense` or `throwOnError` in your queries, you need a way to let queries know that you want to
* try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can
* reset any query errors within the boundaries of the component.
*
* @returns The `children`, rendered as-is, or called with the boundary's {@link QueryErrorResetBoundaryValue}
* if `children` is a function.
*
* @example
* ```tsx
* import { ErrorBoundary } from 'react-error-boundary'
* import { QueryErrorResetBoundary } from '@tanstack/react-query'
*
* function App() {
* return (
* <QueryErrorResetBoundary>
* {({ reset }) => (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* <Page />
* </ErrorBoundary>
* )}
* </QueryErrorResetBoundary>
* )
* }
* ```
*/
const QueryErrorResetBoundary = ({ children }) => {
const [value] = React.useState(() => createValue());
return /* @__PURE__ */ jsx(QueryErrorResetBoundaryContext.Provider, {
value,
children: typeof children === "function" ? children(value) : children
});
};
//#endregion
export { QueryErrorResetBoundary, useQueryErrorResetBoundary };
//# sourceMappingURL=QueryErrorResetBoundary.js.map
@@ -0,0 +1 @@
{"version":3,"file":"QueryErrorResetBoundary.js","names":[],"sources":["../../src/QueryErrorResetBoundary.tsx"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\n// CONTEXT\nexport type QueryErrorResetFunction = () => void\nexport type QueryErrorIsResetFunction = () => boolean\nexport type QueryErrorClearResetFunction = () => void\n\nexport interface QueryErrorResetBoundaryValue {\n clearReset: QueryErrorClearResetFunction\n isReset: QueryErrorIsResetFunction\n reset: QueryErrorResetFunction\n}\n\n/**\n * Resets any query errors within the boundary, so queries know they can try again.\n */\nfunction createValue(): QueryErrorResetBoundaryValue {\n let isReset = false\n return {\n /**\n * Clears the reset state, so queries know not to try again until the boundary is reset again.\n */\n clearReset: () => {\n isReset = false\n },\n /**\n * Resets any query errors within the boundary, so queries know they can try again.\n */\n reset: () => {\n isReset = true\n },\n /**\n * Returns whether the boundary has been reset and not yet cleared.\n */\n isReset: () => {\n return isReset\n },\n }\n}\n\nconst QueryErrorResetBoundaryContext = React.createContext(createValue())\n\n// HOOK\n\n/**\n * This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary\n * defined it will reset them globally.\n *\n * @returns The boundary's {@link QueryErrorResetBoundaryValue}.\n *\n * @example\n * ```tsx\n * import { ErrorBoundary } from 'react-error-boundary'\n * import { useQueryErrorResetBoundary } from '@tanstack/react-query'\n *\n * function App({ children }: { children: React.ReactNode }) {\n * const { reset } = useQueryErrorResetBoundary()\n *\n * return (\n * <ErrorBoundary\n * onReset={reset}\n * fallbackRender={({ resetErrorBoundary }) => (\n * <div>\n * There was an error!\n * <button onClick={() => resetErrorBoundary()}>Try again</button>\n * </div>\n * )}\n * >\n * {children}\n * </ErrorBoundary>\n * )\n * }\n * ```\n */\nexport const useQueryErrorResetBoundary = () =>\n React.useContext(QueryErrorResetBoundaryContext)\n\n// COMPONENT\n\n/**\n * A render-prop function usable as `children` on `QueryErrorResetBoundary`.\n *\n * @param value - The boundary's {@link QueryErrorResetBoundaryValue}.\n * @returns The children to render.\n */\nexport type QueryErrorResetBoundaryFunction = (\n value: QueryErrorResetBoundaryValue,\n) => React.ReactNode\n\n/**\n * The props accepted by `QueryErrorResetBoundary`.\n */\nexport interface QueryErrorResetBoundaryProps {\n /**\n * Either a plain node, or a function that receives the boundary's {@link QueryErrorResetBoundaryValue} and\n * returns a node.\n */\n children: QueryErrorResetBoundaryFunction | React.ReactNode\n}\n\n/**\n * When using `suspense` or `throwOnError` in your queries, you need a way to let queries know that you want to\n * try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can\n * reset any query errors within the boundaries of the component.\n *\n * @returns The `children`, rendered as-is, or called with the boundary's {@link QueryErrorResetBoundaryValue}\n * if `children` is a function.\n *\n * @example\n * ```tsx\n * import { ErrorBoundary } from 'react-error-boundary'\n * import { QueryErrorResetBoundary } from '@tanstack/react-query'\n *\n * function App() {\n * return (\n * <QueryErrorResetBoundary>\n * {({ reset }) => (\n * <ErrorBoundary\n * onReset={reset}\n * fallbackRender={({ resetErrorBoundary }) => (\n * <div>\n * There was an error!\n * <button onClick={() => resetErrorBoundary()}>Try again</button>\n * </div>\n * )}\n * >\n * <Page />\n * </ErrorBoundary>\n * )}\n * </QueryErrorResetBoundary>\n * )\n * }\n * ```\n */\nexport const QueryErrorResetBoundary = ({\n children,\n}: QueryErrorResetBoundaryProps) => {\n const [value] = React.useState(() => createValue())\n return (\n <QueryErrorResetBoundaryContext.Provider value={value}>\n {typeof children === 'function' ? children(value) : children}\n </QueryErrorResetBoundaryContext.Provider>\n )\n}\n"],"mappings":";;;;;;;AAiBA,SAAS,cAA4C;CACnD,IAAI,UAAU;CACd,OAAO;;;;EAIL,kBAAkB;GAChB,UAAU;EACZ;;;;EAIA,aAAa;GACX,UAAU;EACZ;;;;EAIA,eAAe;GACb,OAAO;EACT;CACF;AACF;AAEA,MAAM,iCAAiC,MAAM,cAAc,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCxE,MAAa,mCACX,MAAM,WAAW,8BAA8B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DjD,MAAa,2BAA2B,EACtC,eACkC;CAClC,MAAM,CAAC,SAAS,MAAM,eAAe,YAAY,CAAC;CAClD,OACE,oBAAC,+BAA+B,UAAhC;EAAgD;EAC7C,UAAA,OAAO,aAAa,aAAa,SAAS,KAAK,IAAI;CACb,CAAA;AAE7C"}
@@ -0,0 +1,27 @@
"use client";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_rolldown_runtime = require("./rolldown-runtime-VH7oDXx4.cjs");
let react = require("react");
react = require_rolldown_runtime.__toESM(react, 1);
let _tanstack_query_core = require("@tanstack/query-core");
//#region src/errorBoundaryUtils.ts
const ensurePreventErrorBoundaryRetry = (options, errorResetBoundary, query) => {
const throwOnError = (query === null || query === void 0 ? void 0 : query.state.error) && typeof options.throwOnError === "function" ? (0, _tanstack_query_core.shouldThrowError)(options.throwOnError, [query.state.error, query]) : options.throwOnError;
if (options.suspense || throwOnError) {
if (!errorResetBoundary.isReset()) options.retryOnMount = false;
}
};
const useClearResetErrorBoundary = (errorResetBoundary) => {
react.useEffect(() => {
errorResetBoundary.clearReset();
}, [errorResetBoundary]);
};
const getHasError = ({ result, errorResetBoundary, throwOnError, query, suspense }) => {
return result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && (suspense && result.data === void 0 || (0, _tanstack_query_core.shouldThrowError)(throwOnError, [result.error, query]));
};
//#endregion
exports.ensurePreventErrorBoundaryRetry = ensurePreventErrorBoundaryRetry;
exports.getHasError = getHasError;
exports.useClearResetErrorBoundary = useClearResetErrorBoundary;
//# sourceMappingURL=errorBoundaryUtils.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"errorBoundaryUtils.cjs","names":["shouldThrowError"],"sources":["../../src/errorBoundaryUtils.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\nimport { shouldThrowError } from '@tanstack/query-core'\nimport type {\n DefaultedQueryObserverOptions,\n Query,\n QueryKey,\n QueryObserverResult,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'\n\nexport const ensurePreventErrorBoundaryRetry = <\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey extends QueryKey,\n>(\n options: DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n errorResetBoundary: QueryErrorResetBoundaryValue,\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined,\n) => {\n const throwOnError =\n query?.state.error && typeof options.throwOnError === 'function'\n ? shouldThrowError(options.throwOnError, [query.state.error, query])\n : options.throwOnError\n\n if (options.suspense || throwOnError) {\n // Prevent retrying failed query if the error boundary has not been reset yet\n if (!errorResetBoundary.isReset()) {\n options.retryOnMount = false\n }\n }\n}\n\nexport const useClearResetErrorBoundary = (\n errorResetBoundary: QueryErrorResetBoundaryValue,\n) => {\n React.useEffect(() => {\n errorResetBoundary.clearReset()\n }, [errorResetBoundary])\n}\n\nexport const getHasError = <\n TData,\n TError,\n TQueryFnData,\n TQueryData,\n TQueryKey extends QueryKey,\n>({\n result,\n errorResetBoundary,\n throwOnError,\n query,\n suspense,\n}: {\n result: QueryObserverResult<TData, TError>\n errorResetBoundary: QueryErrorResetBoundaryValue\n throwOnError: ThrowOnError<TQueryFnData, TError, TQueryData, TQueryKey>\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined\n suspense: boolean | undefined\n}) => {\n return (\n result.isError &&\n !errorResetBoundary.isReset() &&\n !result.isFetching &&\n query &&\n ((suspense && result.data === undefined) ||\n shouldThrowError(throwOnError, [result.error, query]))\n )\n}\n"],"mappings":";;;;;;;AAYA,MAAa,mCAOX,SAOA,oBACA,UACG;CACH,MAAM,gBAAA,UAAA,QAAA,UAAA,KAAA,IAAA,KAAA,IACJ,MAAO,MAAM,UAAS,OAAO,QAAQ,iBAAiB,cAAA,GAClDA,qBAAAA,iBAAAA,CAAiB,QAAQ,cAAc,CAAC,MAAM,MAAM,OAAO,KAAK,CAAC,IACjE,QAAQ;CAEd,IAAI,QAAQ,YAAY,cAElB;MAAA,CAAC,mBAAmB,QAAQ,GAC9B,QAAQ,eAAe;CAAA;AAG7B;AAEA,MAAa,8BACX,uBACG;CACH,MAAM,gBAAgB;EACpB,mBAAmB,WAAW;CAChC,GAAG,CAAC,kBAAkB,CAAC;AACzB;AAEA,MAAa,eAMX,EACA,QACA,oBACA,cACA,OACA,eAOI;CACJ,OACE,OAAO,WACP,CAAC,mBAAmB,QAAQ,KAC5B,CAAC,OAAO,cACR,UACE,YAAY,OAAO,SAAS,KAAA,MAAA,GAC5BA,qBAAAA,iBAAAA,CAAiB,cAAc,CAAC,OAAO,OAAO,KAAK,CAAC;AAE1D"}
@@ -0,0 +1,15 @@
import { QueryErrorResetBoundaryValue } from "./QueryErrorResetBoundary.cjs";
import { DefaultedQueryObserverOptions, Query, QueryKey, QueryObserverResult, ThrowOnError } from "@tanstack/query-core";
//#region src/errorBoundaryUtils.d.ts
declare const ensurePreventErrorBoundaryRetry: <TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey>(options: DefaultedQueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>, errorResetBoundary: QueryErrorResetBoundaryValue, query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined) => void;
declare const useClearResetErrorBoundary: (errorResetBoundary: QueryErrorResetBoundaryValue) => void;
declare const getHasError: <TData, TError, TQueryFnData, TQueryData, TQueryKey extends QueryKey>({ result, errorResetBoundary, throwOnError, query, suspense }: {
result: QueryObserverResult<TData, TError>;
errorResetBoundary: QueryErrorResetBoundaryValue;
throwOnError: ThrowOnError<TQueryFnData, TError, TQueryData, TQueryKey>;
query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined;
suspense: boolean | undefined;
}) => boolean | undefined;
//#endregion
export { ensurePreventErrorBoundaryRetry, getHasError, useClearResetErrorBoundary };
//# sourceMappingURL=errorBoundaryUtils.d.cts.map
@@ -0,0 +1 @@
{"version":3,"file":"errorBoundaryUtils.d.cts","names":[],"sources":["../../src/errorBoundaryUtils.ts"],"mappings":";;;cAYa,kCACX,cACA,QACA,OACA,YACA,kBAAkB,UAElB,SAAS,8BACP,cACA,QACA,OACA,YACA,YAEF,oBAAoB,8BACpB,OAAO,MAAM,cAAc,QAAQ,YAAY;cAepC,6BACX,oBAAoB;cAOT,cACX,OACA,QACA,cACA,YACA,kBAAkB,YAClB,QAAA,oBAAA,cAAA,OAAA;EAOA,QAAQ,oBAAoB,OAAO;EACnC,oBAAoB;EACpB,cAAc,aAAa,cAAc,QAAQ,YAAY;EAC7D,OAAO,MAAM,cAAc,QAAQ,YAAY;EAC/C"}
@@ -0,0 +1,15 @@
import { QueryErrorResetBoundaryValue } from "./QueryErrorResetBoundary.js";
import { DefaultedQueryObserverOptions, Query, QueryKey, QueryObserverResult, ThrowOnError } from "@tanstack/query-core";
//#region src/errorBoundaryUtils.d.ts
declare const ensurePreventErrorBoundaryRetry: <TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey>(options: DefaultedQueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>, errorResetBoundary: QueryErrorResetBoundaryValue, query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined) => void;
declare const useClearResetErrorBoundary: (errorResetBoundary: QueryErrorResetBoundaryValue) => void;
declare const getHasError: <TData, TError, TQueryFnData, TQueryData, TQueryKey extends QueryKey>({ result, errorResetBoundary, throwOnError, query, suspense }: {
result: QueryObserverResult<TData, TError>;
errorResetBoundary: QueryErrorResetBoundaryValue;
throwOnError: ThrowOnError<TQueryFnData, TError, TQueryData, TQueryKey>;
query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined;
suspense: boolean | undefined;
}) => boolean | undefined;
//#endregion
export { ensurePreventErrorBoundaryRetry, getHasError, useClearResetErrorBoundary };
//# sourceMappingURL=errorBoundaryUtils.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"errorBoundaryUtils.d.ts","names":[],"sources":["../../src/errorBoundaryUtils.ts"],"mappings":";;;cAYa,kCACX,cACA,QACA,OACA,YACA,kBAAkB,UAElB,SAAS,8BACP,cACA,QACA,OACA,YACA,YAEF,oBAAoB,8BACpB,OAAO,MAAM,cAAc,QAAQ,YAAY;cAepC,6BACX,oBAAoB;cAOT,cACX,OACA,QACA,cACA,YACA,kBAAkB,YAClB,QAAA,oBAAA,cAAA,OAAA;EAOA,QAAQ,oBAAoB,OAAO;EACnC,oBAAoB;EACpB,cAAc,aAAa,cAAc,QAAQ,YAAY;EAC7D,OAAO,MAAM,cAAc,QAAQ,YAAY;EAC/C"}
@@ -0,0 +1,22 @@
"use client";
import * as React from "react";
import { shouldThrowError } from "@tanstack/query-core";
//#region src/errorBoundaryUtils.ts
const ensurePreventErrorBoundaryRetry = (options, errorResetBoundary, query) => {
const throwOnError = (query === null || query === void 0 ? void 0 : query.state.error) && typeof options.throwOnError === "function" ? shouldThrowError(options.throwOnError, [query.state.error, query]) : options.throwOnError;
if (options.suspense || throwOnError) {
if (!errorResetBoundary.isReset()) options.retryOnMount = false;
}
};
const useClearResetErrorBoundary = (errorResetBoundary) => {
React.useEffect(() => {
errorResetBoundary.clearReset();
}, [errorResetBoundary]);
};
const getHasError = ({ result, errorResetBoundary, throwOnError, query, suspense }) => {
return result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && (suspense && result.data === void 0 || shouldThrowError(throwOnError, [result.error, query]));
};
//#endregion
export { ensurePreventErrorBoundaryRetry, getHasError, useClearResetErrorBoundary };
//# sourceMappingURL=errorBoundaryUtils.js.map
@@ -0,0 +1 @@
{"version":3,"file":"errorBoundaryUtils.js","names":[],"sources":["../../src/errorBoundaryUtils.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\nimport { shouldThrowError } from '@tanstack/query-core'\nimport type {\n DefaultedQueryObserverOptions,\n Query,\n QueryKey,\n QueryObserverResult,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'\n\nexport const ensurePreventErrorBoundaryRetry = <\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey extends QueryKey,\n>(\n options: DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n errorResetBoundary: QueryErrorResetBoundaryValue,\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined,\n) => {\n const throwOnError =\n query?.state.error && typeof options.throwOnError === 'function'\n ? shouldThrowError(options.throwOnError, [query.state.error, query])\n : options.throwOnError\n\n if (options.suspense || throwOnError) {\n // Prevent retrying failed query if the error boundary has not been reset yet\n if (!errorResetBoundary.isReset()) {\n options.retryOnMount = false\n }\n }\n}\n\nexport const useClearResetErrorBoundary = (\n errorResetBoundary: QueryErrorResetBoundaryValue,\n) => {\n React.useEffect(() => {\n errorResetBoundary.clearReset()\n }, [errorResetBoundary])\n}\n\nexport const getHasError = <\n TData,\n TError,\n TQueryFnData,\n TQueryData,\n TQueryKey extends QueryKey,\n>({\n result,\n errorResetBoundary,\n throwOnError,\n query,\n suspense,\n}: {\n result: QueryObserverResult<TData, TError>\n errorResetBoundary: QueryErrorResetBoundaryValue\n throwOnError: ThrowOnError<TQueryFnData, TError, TQueryData, TQueryKey>\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined\n suspense: boolean | undefined\n}) => {\n return (\n result.isError &&\n !errorResetBoundary.isReset() &&\n !result.isFetching &&\n query &&\n ((suspense && result.data === undefined) ||\n shouldThrowError(throwOnError, [result.error, query]))\n )\n}\n"],"mappings":";;;;AAYA,MAAa,mCAOX,SAOA,oBACA,UACG;CACH,MAAM,gBAAA,UAAA,QAAA,UAAA,KAAA,IAAA,KAAA,IACJ,MAAO,MAAM,UAAS,OAAO,QAAQ,iBAAiB,aAClD,iBAAiB,QAAQ,cAAc,CAAC,MAAM,MAAM,OAAO,KAAK,CAAC,IACjE,QAAQ;CAEd,IAAI,QAAQ,YAAY,cAElB;MAAA,CAAC,mBAAmB,QAAQ,GAC9B,QAAQ,eAAe;CAAA;AAG7B;AAEA,MAAa,8BACX,uBACG;CACH,MAAM,gBAAgB;EACpB,mBAAmB,WAAW;CAChC,GAAG,CAAC,kBAAkB,CAAC;AACzB;AAEA,MAAa,eAMX,EACA,QACA,oBACA,cACA,OACA,eAOI;CACJ,OACE,OAAO,WACP,CAAC,mBAAmB,QAAQ,KAC5B,CAAC,OAAO,cACR,UACE,YAAY,OAAO,SAAS,KAAA,KAC5B,iBAAiB,cAAc,CAAC,OAAO,OAAO,KAAK,CAAC;AAE1D"}
+56
View File
@@ -0,0 +1,56 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_QueryClientProvider = require("./QueryClientProvider.cjs");
const require_HydrationBoundary = require("./HydrationBoundary.cjs");
const require_IsRestoringProvider = require("./IsRestoringProvider.cjs");
const require_QueryErrorResetBoundary = require("./QueryErrorResetBoundary.cjs");
const require_useQueries = require("./useQueries.cjs");
const require_useQuery = require("./useQuery.cjs");
const require_useSuspenseQuery = require("./useSuspenseQuery.cjs");
const require_useSuspenseInfiniteQuery = require("./useSuspenseInfiniteQuery.cjs");
const require_useSuspenseQueries = require("./useSuspenseQueries.cjs");
const require_usePrefetchQuery = require("./usePrefetchQuery.cjs");
const require_usePrefetchInfiniteQuery = require("./usePrefetchInfiniteQuery.cjs");
const require_queryOptions = require("./queryOptions.cjs");
const require_infiniteQueryOptions = require("./infiniteQueryOptions.cjs");
const require_useIsFetching = require("./useIsFetching.cjs");
const require_useMutationState = require("./useMutationState.cjs");
const require_useMutation = require("./useMutation.cjs");
const require_mutationOptions = require("./mutationOptions.cjs");
const require_useInfiniteQuery = require("./useInfiniteQuery.cjs");
//#region src/index.ts
/* istanbul ignore file */
//#endregion
exports.HydrationBoundary = require_HydrationBoundary.HydrationBoundary;
exports.IsRestoringProvider = require_IsRestoringProvider.IsRestoringProvider;
exports.QueryClientContext = require_QueryClientProvider.QueryClientContext;
exports.QueryClientProvider = require_QueryClientProvider.QueryClientProvider;
exports.QueryErrorResetBoundary = require_QueryErrorResetBoundary.QueryErrorResetBoundary;
exports.infiniteQueryOptions = require_infiniteQueryOptions.infiniteQueryOptions;
exports.mutationOptions = require_mutationOptions.mutationOptions;
exports.queryOptions = require_queryOptions.queryOptions;
exports.useInfiniteQuery = require_useInfiniteQuery.useInfiniteQuery;
exports.useIsFetching = require_useIsFetching.useIsFetching;
exports.useIsMutating = require_useMutationState.useIsMutating;
exports.useIsRestoring = require_IsRestoringProvider.useIsRestoring;
exports.useMutation = require_useMutation.useMutation;
exports.useMutationState = require_useMutationState.useMutationState;
exports.usePrefetchInfiniteQuery = require_usePrefetchInfiniteQuery.usePrefetchInfiniteQuery;
exports.usePrefetchQuery = require_usePrefetchQuery.usePrefetchQuery;
exports.useQueries = require_useQueries.useQueries;
exports.useQuery = require_useQuery.useQuery;
exports.useQueryClient = require_QueryClientProvider.useQueryClient;
exports.useQueryErrorResetBoundary = require_QueryErrorResetBoundary.useQueryErrorResetBoundary;
exports.useSuspenseInfiniteQuery = require_useSuspenseInfiniteQuery.useSuspenseInfiniteQuery;
exports.useSuspenseQueries = require_useSuspenseQueries.useSuspenseQueries;
exports.useSuspenseQuery = require_useSuspenseQuery.useSuspenseQuery;
var _tanstack_query_core = require("@tanstack/query-core");
Object.keys(_tanstack_query_core).forEach(function(k) {
if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function() {
return _tanstack_query_core[k];
}
});
});
//# sourceMappingURL=index.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\n// Re-export core\nexport * from '@tanstack/query-core'\n\n// React Query\nexport type * from './types'\nexport { useQueries } from './useQueries'\nexport type { QueriesResults, QueriesOptions } from './useQueries'\nexport { useQuery } from './useQuery'\nexport { useSuspenseQuery } from './useSuspenseQuery'\nexport { useSuspenseInfiniteQuery } from './useSuspenseInfiniteQuery'\nexport { useSuspenseQueries } from './useSuspenseQueries'\nexport type {\n SuspenseQueriesResults,\n SuspenseQueriesOptions,\n} from './useSuspenseQueries'\nexport { usePrefetchQuery } from './usePrefetchQuery'\nexport { usePrefetchInfiniteQuery } from './usePrefetchInfiniteQuery'\nexport { queryOptions } from './queryOptions'\nexport type {\n DefinedInitialDataOptions,\n UndefinedInitialDataOptions,\n UnusedSkipTokenOptions,\n} from './queryOptions'\nexport { infiniteQueryOptions } from './infiniteQueryOptions'\nexport type {\n DefinedInitialDataInfiniteOptions,\n UndefinedInitialDataInfiniteOptions,\n UnusedSkipTokenInfiniteOptions,\n} from './infiniteQueryOptions'\nexport {\n QueryClientContext,\n QueryClientProvider,\n useQueryClient,\n} from './QueryClientProvider'\nexport type { QueryClientProviderProps } from './QueryClientProvider'\nexport type { QueryErrorResetBoundaryProps } from './QueryErrorResetBoundary'\nexport { HydrationBoundary } from './HydrationBoundary'\nexport type { HydrationBoundaryProps } from './HydrationBoundary'\nexport type {\n QueryErrorClearResetFunction,\n QueryErrorIsResetFunction,\n QueryErrorResetBoundaryFunction,\n QueryErrorResetFunction,\n} from './QueryErrorResetBoundary'\nexport {\n QueryErrorResetBoundary,\n useQueryErrorResetBoundary,\n} from './QueryErrorResetBoundary'\nexport { useIsFetching } from './useIsFetching'\nexport { useIsMutating, useMutationState } from './useMutationState'\nexport { useMutation } from './useMutation'\nexport { mutationOptions } from './mutationOptions'\nexport { useInfiniteQuery } from './useInfiniteQuery'\nexport { useIsRestoring, IsRestoringProvider } from './IsRestoringProvider'\n"],"mappings":""}
+21
View File
@@ -0,0 +1,21 @@
import { HydrationBoundary, HydrationBoundaryProps } from "./HydrationBoundary.cjs";
import { IsRestoringProvider, useIsRestoring } from "./IsRestoringProvider.cjs";
import { QueryClientContext, QueryClientProvider, QueryClientProviderProps, useQueryClient } from "./QueryClientProvider.cjs";
import { QueryErrorClearResetFunction, QueryErrorIsResetFunction, QueryErrorResetBoundary, QueryErrorResetBoundaryFunction, QueryErrorResetBoundaryProps, QueryErrorResetFunction, useQueryErrorResetBoundary } from "./QueryErrorResetBoundary.cjs";
import { AnyUseBaseQueryOptions, AnyUseInfiniteQueryOptions, AnyUseMutationOptions, AnyUseQueryOptions, AnyUseSuspenseInfiniteQueryOptions, AnyUseSuspenseQueryOptions, DefinedUseInfiniteQueryResult, DefinedUseQueryResult, UseBaseMutationResult, UseBaseQueryOptions, UseBaseQueryResult, UseInfiniteQueryOptions, UseInfiniteQueryResult, UseMutateAsyncFunction, UseMutateFunction, UseMutationOptions, UseMutationResult, UsePrefetchInfiniteQueryOptions, UsePrefetchQueryOptions, UseQueryOptions, UseQueryResult, UseSuspenseInfiniteQueryOptions, UseSuspenseInfiniteQueryResult, UseSuspenseQueryOptions, UseSuspenseQueryResult } from "./types.cjs";
import { QueriesOptions, QueriesResults, useQueries } from "./useQueries.cjs";
import { DefinedInitialDataOptions, UndefinedInitialDataOptions, UnusedSkipTokenOptions, queryOptions } from "./queryOptions.cjs";
import { useQuery } from "./useQuery.cjs";
import { useSuspenseQuery } from "./useSuspenseQuery.cjs";
import { useSuspenseInfiniteQuery } from "./useSuspenseInfiniteQuery.cjs";
import { SuspenseQueriesOptions, SuspenseQueriesResults, useSuspenseQueries } from "./useSuspenseQueries.cjs";
import { usePrefetchQuery } from "./usePrefetchQuery.cjs";
import { usePrefetchInfiniteQuery } from "./usePrefetchInfiniteQuery.cjs";
import { DefinedInitialDataInfiniteOptions, UndefinedInitialDataInfiniteOptions, UnusedSkipTokenInfiniteOptions, infiniteQueryOptions } from "./infiniteQueryOptions.cjs";
import { useIsFetching } from "./useIsFetching.cjs";
import { useIsMutating, useMutationState } from "./useMutationState.cjs";
import { useMutation } from "./useMutation.cjs";
import { mutationOptions } from "./mutationOptions.cjs";
import { useInfiniteQuery } from "./useInfiniteQuery.cjs";
export * from "@tanstack/query-core";
export { type AnyUseBaseQueryOptions, type AnyUseInfiniteQueryOptions, type AnyUseMutationOptions, type AnyUseQueryOptions, type AnyUseSuspenseInfiniteQueryOptions, type AnyUseSuspenseQueryOptions, type DefinedInitialDataInfiniteOptions, type DefinedInitialDataOptions, type DefinedUseInfiniteQueryResult, type DefinedUseQueryResult, HydrationBoundary, type HydrationBoundaryProps, IsRestoringProvider, type QueriesOptions, type QueriesResults, QueryClientContext, QueryClientProvider, type QueryClientProviderProps, type QueryErrorClearResetFunction, type QueryErrorIsResetFunction, QueryErrorResetBoundary, type QueryErrorResetBoundaryFunction, type QueryErrorResetBoundaryProps, type QueryErrorResetFunction, type SuspenseQueriesOptions, type SuspenseQueriesResults, type UndefinedInitialDataInfiniteOptions, type UndefinedInitialDataOptions, type UnusedSkipTokenInfiniteOptions, type UnusedSkipTokenOptions, type UseBaseMutationResult, type UseBaseQueryOptions, type UseBaseQueryResult, type UseInfiniteQueryOptions, type UseInfiniteQueryResult, type UseMutateAsyncFunction, type UseMutateFunction, type UseMutationOptions, type UseMutationResult, type UsePrefetchInfiniteQueryOptions, type UsePrefetchQueryOptions, type UseQueryOptions, type UseQueryResult, type UseSuspenseInfiniteQueryOptions, type UseSuspenseInfiniteQueryResult, type UseSuspenseQueryOptions, type UseSuspenseQueryResult, infiniteQueryOptions, mutationOptions, queryOptions, useInfiniteQuery, useIsFetching, useIsMutating, useIsRestoring, useMutation, useMutationState, usePrefetchInfiniteQuery, usePrefetchQuery, useQueries, useQuery, useQueryClient, useQueryErrorResetBoundary, useSuspenseInfiniteQuery, useSuspenseQueries, useSuspenseQuery };
+21
View File
@@ -0,0 +1,21 @@
import { HydrationBoundary, HydrationBoundaryProps } from "./HydrationBoundary.js";
import { IsRestoringProvider, useIsRestoring } from "./IsRestoringProvider.js";
import { QueryClientContext, QueryClientProvider, QueryClientProviderProps, useQueryClient } from "./QueryClientProvider.js";
import { QueryErrorClearResetFunction, QueryErrorIsResetFunction, QueryErrorResetBoundary, QueryErrorResetBoundaryFunction, QueryErrorResetBoundaryProps, QueryErrorResetFunction, useQueryErrorResetBoundary } from "./QueryErrorResetBoundary.js";
import { AnyUseBaseQueryOptions, AnyUseInfiniteQueryOptions, AnyUseMutationOptions, AnyUseQueryOptions, AnyUseSuspenseInfiniteQueryOptions, AnyUseSuspenseQueryOptions, DefinedUseInfiniteQueryResult, DefinedUseQueryResult, UseBaseMutationResult, UseBaseQueryOptions, UseBaseQueryResult, UseInfiniteQueryOptions, UseInfiniteQueryResult, UseMutateAsyncFunction, UseMutateFunction, UseMutationOptions, UseMutationResult, UsePrefetchInfiniteQueryOptions, UsePrefetchQueryOptions, UseQueryOptions, UseQueryResult, UseSuspenseInfiniteQueryOptions, UseSuspenseInfiniteQueryResult, UseSuspenseQueryOptions, UseSuspenseQueryResult } from "./types.js";
import { QueriesOptions, QueriesResults, useQueries } from "./useQueries.js";
import { DefinedInitialDataOptions, UndefinedInitialDataOptions, UnusedSkipTokenOptions, queryOptions } from "./queryOptions.js";
import { useQuery } from "./useQuery.js";
import { useSuspenseQuery } from "./useSuspenseQuery.js";
import { useSuspenseInfiniteQuery } from "./useSuspenseInfiniteQuery.js";
import { SuspenseQueriesOptions, SuspenseQueriesResults, useSuspenseQueries } from "./useSuspenseQueries.js";
import { usePrefetchQuery } from "./usePrefetchQuery.js";
import { usePrefetchInfiniteQuery } from "./usePrefetchInfiniteQuery.js";
import { DefinedInitialDataInfiniteOptions, UndefinedInitialDataInfiniteOptions, UnusedSkipTokenInfiniteOptions, infiniteQueryOptions } from "./infiniteQueryOptions.js";
import { useIsFetching } from "./useIsFetching.js";
import { useIsMutating, useMutationState } from "./useMutationState.js";
import { useMutation } from "./useMutation.js";
import { mutationOptions } from "./mutationOptions.js";
import { useInfiniteQuery } from "./useInfiniteQuery.js";
export * from "@tanstack/query-core";
export { type AnyUseBaseQueryOptions, type AnyUseInfiniteQueryOptions, type AnyUseMutationOptions, type AnyUseQueryOptions, type AnyUseSuspenseInfiniteQueryOptions, type AnyUseSuspenseQueryOptions, type DefinedInitialDataInfiniteOptions, type DefinedInitialDataOptions, type DefinedUseInfiniteQueryResult, type DefinedUseQueryResult, HydrationBoundary, type HydrationBoundaryProps, IsRestoringProvider, type QueriesOptions, type QueriesResults, QueryClientContext, QueryClientProvider, type QueryClientProviderProps, type QueryErrorClearResetFunction, type QueryErrorIsResetFunction, QueryErrorResetBoundary, type QueryErrorResetBoundaryFunction, type QueryErrorResetBoundaryProps, type QueryErrorResetFunction, type SuspenseQueriesOptions, type SuspenseQueriesResults, type UndefinedInitialDataInfiniteOptions, type UndefinedInitialDataOptions, type UnusedSkipTokenInfiniteOptions, type UnusedSkipTokenOptions, type UseBaseMutationResult, type UseBaseQueryOptions, type UseBaseQueryResult, type UseInfiniteQueryOptions, type UseInfiniteQueryResult, type UseMutateAsyncFunction, type UseMutateFunction, type UseMutationOptions, type UseMutationResult, type UsePrefetchInfiniteQueryOptions, type UsePrefetchQueryOptions, type UseQueryOptions, type UseQueryResult, type UseSuspenseInfiniteQueryOptions, type UseSuspenseInfiniteQueryResult, type UseSuspenseQueryOptions, type UseSuspenseQueryResult, infiniteQueryOptions, mutationOptions, queryOptions, useInfiniteQuery, useIsFetching, useIsMutating, useIsRestoring, useMutation, useMutationState, usePrefetchInfiniteQuery, usePrefetchQuery, useQueries, useQuery, useQueryClient, useQueryErrorResetBoundary, useSuspenseInfiniteQuery, useSuspenseQueries, useSuspenseQuery };
+25
View File
@@ -0,0 +1,25 @@
import { QueryClientContext, QueryClientProvider, useQueryClient } from "./QueryClientProvider.js";
import { HydrationBoundary } from "./HydrationBoundary.js";
import { IsRestoringProvider, useIsRestoring } from "./IsRestoringProvider.js";
import { QueryErrorResetBoundary, useQueryErrorResetBoundary } from "./QueryErrorResetBoundary.js";
import { useQueries } from "./useQueries.js";
import { useQuery } from "./useQuery.js";
import { useSuspenseQuery } from "./useSuspenseQuery.js";
import { useSuspenseInfiniteQuery } from "./useSuspenseInfiniteQuery.js";
import { useSuspenseQueries } from "./useSuspenseQueries.js";
import { usePrefetchQuery } from "./usePrefetchQuery.js";
import { usePrefetchInfiniteQuery } from "./usePrefetchInfiniteQuery.js";
import { queryOptions } from "./queryOptions.js";
import { infiniteQueryOptions } from "./infiniteQueryOptions.js";
import { useIsFetching } from "./useIsFetching.js";
import { useIsMutating, useMutationState } from "./useMutationState.js";
import { useMutation } from "./useMutation.js";
import { mutationOptions } from "./mutationOptions.js";
import { useInfiniteQuery } from "./useInfiniteQuery.js";
export * from "@tanstack/query-core";
//#region src/index.ts
/* istanbul ignore file */
//#endregion
export { HydrationBoundary, IsRestoringProvider, QueryClientContext, QueryClientProvider, QueryErrorResetBoundary, infiniteQueryOptions, mutationOptions, queryOptions, useInfiniteQuery, useIsFetching, useIsMutating, useIsRestoring, useMutation, useMutationState, usePrefetchInfiniteQuery, usePrefetchQuery, useQueries, useQuery, useQueryClient, useQueryErrorResetBoundary, useSuspenseInfiniteQuery, useSuspenseQueries, useSuspenseQuery };
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\n// Re-export core\nexport * from '@tanstack/query-core'\n\n// React Query\nexport type * from './types'\nexport { useQueries } from './useQueries'\nexport type { QueriesResults, QueriesOptions } from './useQueries'\nexport { useQuery } from './useQuery'\nexport { useSuspenseQuery } from './useSuspenseQuery'\nexport { useSuspenseInfiniteQuery } from './useSuspenseInfiniteQuery'\nexport { useSuspenseQueries } from './useSuspenseQueries'\nexport type {\n SuspenseQueriesResults,\n SuspenseQueriesOptions,\n} from './useSuspenseQueries'\nexport { usePrefetchQuery } from './usePrefetchQuery'\nexport { usePrefetchInfiniteQuery } from './usePrefetchInfiniteQuery'\nexport { queryOptions } from './queryOptions'\nexport type {\n DefinedInitialDataOptions,\n UndefinedInitialDataOptions,\n UnusedSkipTokenOptions,\n} from './queryOptions'\nexport { infiniteQueryOptions } from './infiniteQueryOptions'\nexport type {\n DefinedInitialDataInfiniteOptions,\n UndefinedInitialDataInfiniteOptions,\n UnusedSkipTokenInfiniteOptions,\n} from './infiniteQueryOptions'\nexport {\n QueryClientContext,\n QueryClientProvider,\n useQueryClient,\n} from './QueryClientProvider'\nexport type { QueryClientProviderProps } from './QueryClientProvider'\nexport type { QueryErrorResetBoundaryProps } from './QueryErrorResetBoundary'\nexport { HydrationBoundary } from './HydrationBoundary'\nexport type { HydrationBoundaryProps } from './HydrationBoundary'\nexport type {\n QueryErrorClearResetFunction,\n QueryErrorIsResetFunction,\n QueryErrorResetBoundaryFunction,\n QueryErrorResetFunction,\n} from './QueryErrorResetBoundary'\nexport {\n QueryErrorResetBoundary,\n useQueryErrorResetBoundary,\n} from './QueryErrorResetBoundary'\nexport { useIsFetching } from './useIsFetching'\nexport { useIsMutating, useMutationState } from './useMutationState'\nexport { useMutation } from './useMutation'\nexport { mutationOptions } from './mutationOptions'\nexport { useInfiniteQuery } from './useInfiniteQuery'\nexport { useIsRestoring, IsRestoringProvider } from './IsRestoringProvider'\n"],"mappings":""}
@@ -0,0 +1,9 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
//#region src/infiniteQueryOptions.ts
function infiniteQueryOptions(options) {
return options;
}
//#endregion
exports.infiniteQueryOptions = infiniteQueryOptions;
//# sourceMappingURL=infiniteQueryOptions.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"infiniteQueryOptions.cjs","names":[],"sources":["../../src/infiniteQueryOptions.ts"],"sourcesContent":["import type {\n DefaultError,\n InfiniteData,\n InitialDataFunction,\n NonUndefinedGuard,\n OmitKeyof,\n QueryKey,\n QueryKeyWithDataTag,\n SkipToken,\n} from '@tanstack/query-core'\nimport type { UseInfiniteQueryOptions } from './types'\n\n/**\n * The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set — `data`\n * may be `undefined` while the query is `pending`.\n *\n * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,\n * the shape of all fetched pages plus their page params.\n * @template TQueryKey - The type of your `queryKey`.\n * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.\n */\nexport type UndefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> = UseInfiniteQueryOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n> & {\n /**\n * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been\n * created or cached yet). If set to a function, the function will be called **once** during the shared/root\n * query initialization, and be expected to synchronously return the initial data. Initial data is\n * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the\n * cache.\n */\n initialData?:\n | undefined\n | NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>\n | InitialDataFunction<\n NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>\n >\n}\n\n/**\n * The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set and\n * `queryFn` is not `skipToken` — same as {@link UndefinedInitialDataInfiniteOptions}, but `queryFn` may not be\n * `skipToken`.\n *\n * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,\n * the shape of all fetched pages plus their page params.\n * @template TQueryKey - The type of your `queryKey`.\n * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.\n */\nexport type UnusedSkipTokenInfiniteOptions<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> = OmitKeyof<\n UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>,\n 'queryFn'\n> & {\n /**\n * `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If\n * you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a\n * fetch that fails with \"Missing queryFn\" unless `enabled` is `false` or a default query function has been\n * defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own.\n */\n queryFn?: Exclude<\n UseInfiniteQueryOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >['queryFn'],\n SkipToken | undefined\n >\n}\n\n/**\n * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is set — `data` is\n * never `undefined`.\n *\n * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,\n * the shape of all fetched pages plus their page params.\n * @template TQueryKey - The type of your `queryKey`.\n * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.\n */\nexport type DefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> = UseInfiniteQueryOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n> & {\n /**\n * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been\n * created or cached yet). If set to a function, the function will be called **once** during the shared/root\n * query initialization, and be expected to synchronously return the initial data. Initial data is\n * considered stale by default unless aLine truncated
@@ -0,0 +1,191 @@
import { UseInfiniteQueryOptions } from "./types.cjs";
import { DefaultError, InfiniteData, InitialDataFunction, NonUndefinedGuard, OmitKeyof, QueryKey, QueryKeyWithDataTag, SkipToken } from "@tanstack/query-core";
//#region src/infiniteQueryOptions.d.ts
/**
* The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set — `data`
* may be `undefined` while the query is `pending`.
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
type UndefinedInitialDataInfiniteOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> = UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & {
/**
* If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
* created or cached yet). If set to a function, the function will be called **once** during the shared/root
* query initialization, and be expected to synchronously return the initial data. Initial data is
* considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
* cache.
*/
initialData?: undefined | NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>> | InitialDataFunction<NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>>;
};
/**
* The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set and
* `queryFn` is not `skipToken` — same as {@link UndefinedInitialDataInfiniteOptions}, but `queryFn` may not be
* `skipToken`.
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
type UnusedSkipTokenInfiniteOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> = OmitKeyof<UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, 'queryFn'> & {
/**
* `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If
* you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a
* fetch that fails with "Missing queryFn" unless `enabled` is `false` or a default query function has been
* defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own.
*/
queryFn?: Exclude<UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>['queryFn'], SkipToken | undefined>;
};
/**
* The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is set — `data` is
* never `undefined`.
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
type DefinedInitialDataInfiniteOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> = UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & {
/**
* If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
* created or cached yet). If set to a function, the function will be called **once** during the shared/root
* query initialization, and be expected to synchronously return the initial data. Initial data is
* considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
* cache.
*/
initialData: NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>> | (() => NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>) | undefined;
};
/**
* You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.
* These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`.
* `options.queryKey` is required and is the query key to generate options for.
*
* This overload is selected when `initialData` is set.
*
* @see {@link useInfiniteQuery} to run an infinite query with these options.
* @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` set.
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
* @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or
* automatically as the user scrolls.
*
* @example
* ```tsx
* import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query'
*
* export const projectsOptions = infiniteQueryOptions({
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* initialData: { pages: [], pageParams: [] },
* })
*
* function Projects() {
* // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
* // list stays visible alongside the error.
* const { data, isError, error } = useInfiniteQuery(projectsOptions)
*
* return (
* <div>
* {isError ? <span>Error: {error.message}</span> : null}
* <ul>
* {data.pages.map((page) => page.projects.map((p) => <li key={p.id}>{p.name}</li>))}
* </ul>
* </div>
* )
* }
* ```
*/
declare function infiniteQueryOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>;
/**
* You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.
* These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`.
* `options.queryKey` is required and is the query key to generate options for.
*
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
* @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or
* automatically as the user scrolls.
*
* @example
* A parameterized factory, so the same options object can be reused per `postId`:
* ```tsx
* import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query'
*
* export const commentsOptions = (postId: string) =>
* infiniteQueryOptions({
* queryKey: ['post', postId, 'comments'],
* queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* })
*
* function Comments({ postId }: { postId: string }) {
* const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId))
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return (
* <ul>
* {data.pages.map((page) => page.comments.map((c) => <li key={c.id}>{c.text}</li>))}
* </ul>
* )
* }
* ```
*
* @see {@link useInfiniteQuery} to run an infinite query with these options.
* @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`.
*/
declare function infiniteQueryOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: UnusedSkipTokenInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): UnusedSkipTokenInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>;
/**
* You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.
* These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`.
* `options.queryKey` is required and is the query key to generate options for.
*
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
* @remarks See {@link useInfiniteQuery} for examples that fetch further pages (from a button click or
* automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set.
*
* @example
* A parameterized factory, so the same options object can be reused per `postId`:
* ```tsx
* import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query'
*
* export const commentsOptions = (postId: string) =>
* infiniteQueryOptions({
* queryKey: ['post', postId, 'comments'],
* queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* })
*
* function Comments({ postId }: { postId: string }) {
* const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId))
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return (
* <ul>
* {data.pages.map((page) => page.comments.map((c) => <li key={c.id}>{c.text}</li>))}
* </ul>
* )
* }
* ```
*
* @see {@link useInfiniteQuery} to run an infinite query with these options.
* @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`.
*/
declare function infiniteQueryOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>;
//#endregion
export { DefinedInitialDataInfiniteOptions, UndefinedInitialDataInfiniteOptions, UnusedSkipTokenInfiniteOptions, infiniteQueryOptions };
//# sourceMappingURL=infiniteQueryOptions.d.cts.map
@@ -0,0 +1 @@
{"version":3,"file":"infiniteQueryOptions.d.cts","names":[],"sources":["../../src/infiniteQueryOptions.ts"],"mappings":";;;;;;;;;;;;;;KAuBY,oCACV,cACA,SAAS,cACT,QAAQ,aAAa,eACrB,kBAAkB,WAAW,UAC7B,wBACE,wBACF,cACA,QACA,OACA,WACA;;;;;;;;EASA,0BAEI,kBAAkB,aAAa,cAAc,eAC7C,oBACE,kBAAkB,aAAa,cAAc;;;;;;;;;;;;;;KAgBzC,+BACV,cACA,SAAS,cACT,QAAQ,aAAa,eACrB,kBAAkB,WAAW,UAC7B,wBACE,UACF,wBAAwB,cAAc,QAAQ,OAAO,WAAW;;;;;;;EAShE,UAAU,QACR,wBACE,cACA,QACA,OACA,WACA,wBAEF;;;;;;;;;;;;;KAeQ,kCACV,cACA,SAAS,cACT,QAAQ,aAAa,eACrB,kBAAkB,WAAW,UAC7B,wBACE,wBACF,cACA,QACA,OACA,WACA;;;;;;;;EASA,aACI,kBAAkB,aAAa,cAAc,sBACtC,kBAAkB,aAAa,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6C1C,qBACd,cACA,SAAS,cACT,QAAQ,aAAa,eACrB,kBAAkB,WAAW,UAC7B,sBAEA,SAAS,kCACP,cACA,QACA,OACA,WACA,cAED,kCACD,cACA,QACA,OACA,WACA,cAEA,oBAAoB,WAAW,aAAa,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyC7C,qBACd,cACA,SAAS,cACT,QAAQ,aAAa,eACrB,kBAAkB,WAAW,UAC7B,sBAEA,SAAS,+BACP,cACA,QACA,OACA,WACA,cAED,+BACD,cACA,QACA,OACA,WACA,cAEA,oBAAoB,WAAW,aAAa,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyC7C,qBACd,cACA,SAAS,cACT,QAAQ,aAAa,eACrB,kBAAkB,WAAW,UAC7B,sBAEA,SAAS,oCACP,cACA,QACA,OACA,WACA,cAED,oCACD,cACA,QACA,OACA,WACA,cAEA,oBAAoB,WAAW,aAAa,eAAe"}
@@ -0,0 +1,191 @@
import { UseInfiniteQueryOptions } from "./types.js";
import { DefaultError, InfiniteData, InitialDataFunction, NonUndefinedGuard, OmitKeyof, QueryKey, QueryKeyWithDataTag, SkipToken } from "@tanstack/query-core";
//#region src/infiniteQueryOptions.d.ts
/**
* The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set — `data`
* may be `undefined` while the query is `pending`.
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
type UndefinedInitialDataInfiniteOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> = UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & {
/**
* If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
* created or cached yet). If set to a function, the function will be called **once** during the shared/root
* query initialization, and be expected to synchronously return the initial data. Initial data is
* considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
* cache.
*/
initialData?: undefined | NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>> | InitialDataFunction<NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>>;
};
/**
* The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set and
* `queryFn` is not `skipToken` — same as {@link UndefinedInitialDataInfiniteOptions}, but `queryFn` may not be
* `skipToken`.
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
type UnusedSkipTokenInfiniteOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> = OmitKeyof<UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, 'queryFn'> & {
/**
* `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If
* you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a
* fetch that fails with "Missing queryFn" unless `enabled` is `false` or a default query function has been
* defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own.
*/
queryFn?: Exclude<UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>['queryFn'], SkipToken | undefined>;
};
/**
* The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is set — `data` is
* never `undefined`.
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
type DefinedInitialDataInfiniteOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> = UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & {
/**
* If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
* created or cached yet). If set to a function, the function will be called **once** during the shared/root
* query initialization, and be expected to synchronously return the initial data. Initial data is
* considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
* cache.
*/
initialData: NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>> | (() => NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>) | undefined;
};
/**
* You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.
* These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`.
* `options.queryKey` is required and is the query key to generate options for.
*
* This overload is selected when `initialData` is set.
*
* @see {@link useInfiniteQuery} to run an infinite query with these options.
* @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` set.
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
* @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or
* automatically as the user scrolls.
*
* @example
* ```tsx
* import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query'
*
* export const projectsOptions = infiniteQueryOptions({
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* initialData: { pages: [], pageParams: [] },
* })
*
* function Projects() {
* // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
* // list stays visible alongside the error.
* const { data, isError, error } = useInfiniteQuery(projectsOptions)
*
* return (
* <div>
* {isError ? <span>Error: {error.message}</span> : null}
* <ul>
* {data.pages.map((page) => page.projects.map((p) => <li key={p.id}>{p.name}</li>))}
* </ul>
* </div>
* )
* }
* ```
*/
declare function infiniteQueryOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>;
/**
* You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.
* These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`.
* `options.queryKey` is required and is the query key to generate options for.
*
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
* @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or
* automatically as the user scrolls.
*
* @example
* A parameterized factory, so the same options object can be reused per `postId`:
* ```tsx
* import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query'
*
* export const commentsOptions = (postId: string) =>
* infiniteQueryOptions({
* queryKey: ['post', postId, 'comments'],
* queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* })
*
* function Comments({ postId }: { postId: string }) {
* const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId))
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return (
* <ul>
* {data.pages.map((page) => page.comments.map((c) => <li key={c.id}>{c.text}</li>))}
* </ul>
* )
* }
* ```
*
* @see {@link useInfiniteQuery} to run an infinite query with these options.
* @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`.
*/
declare function infiniteQueryOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: UnusedSkipTokenInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): UnusedSkipTokenInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>;
/**
* You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.
* These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`.
* `options.queryKey` is required and is the query key to generate options for.
*
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
* @remarks See {@link useInfiniteQuery} for examples that fetch further pages (from a button click or
* automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set.
*
* @example
* A parameterized factory, so the same options object can be reused per `postId`:
* ```tsx
* import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query'
*
* export const commentsOptions = (postId: string) =>
* infiniteQueryOptions({
* queryKey: ['post', postId, 'comments'],
* queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* })
*
* function Comments({ postId }: { postId: string }) {
* const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId))
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return (
* <ul>
* {data.pages.map((page) => page.comments.map((c) => <li key={c.id}>{c.text}</li>))}
* </ul>
* )
* }
* ```
*
* @see {@link useInfiniteQuery} to run an infinite query with these options.
* @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`.
*/
declare function infiniteQueryOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>;
//#endregion
export { DefinedInitialDataInfiniteOptions, UndefinedInitialDataInfiniteOptions, UnusedSkipTokenInfiniteOptions, infiniteQueryOptions };
//# sourceMappingURL=infiniteQueryOptions.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"infiniteQueryOptions.d.ts","names":[],"sources":["../../src/infiniteQueryOptions.ts"],"mappings":";;;;;;;;;;;;;;KAuBY,oCACV,cACA,SAAS,cACT,QAAQ,aAAa,eACrB,kBAAkB,WAAW,UAC7B,wBACE,wBACF,cACA,QACA,OACA,WACA;;;;;;;;EASA,0BAEI,kBAAkB,aAAa,cAAc,eAC7C,oBACE,kBAAkB,aAAa,cAAc;;;;;;;;;;;;;;KAgBzC,+BACV,cACA,SAAS,cACT,QAAQ,aAAa,eACrB,kBAAkB,WAAW,UAC7B,wBACE,UACF,wBAAwB,cAAc,QAAQ,OAAO,WAAW;;;;;;;EAShE,UAAU,QACR,wBACE,cACA,QACA,OACA,WACA,wBAEF;;;;;;;;;;;;;KAeQ,kCACV,cACA,SAAS,cACT,QAAQ,aAAa,eACrB,kBAAkB,WAAW,UAC7B,wBACE,wBACF,cACA,QACA,OACA,WACA;;;;;;;;EASA,aACI,kBAAkB,aAAa,cAAc,sBACtC,kBAAkB,aAAa,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6C1C,qBACd,cACA,SAAS,cACT,QAAQ,aAAa,eACrB,kBAAkB,WAAW,UAC7B,sBAEA,SAAS,kCACP,cACA,QACA,OACA,WACA,cAED,kCACD,cACA,QACA,OACA,WACA,cAEA,oBAAoB,WAAW,aAAa,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyC7C,qBACd,cACA,SAAS,cACT,QAAQ,aAAa,eACrB,kBAAkB,WAAW,UAC7B,sBAEA,SAAS,+BACP,cACA,QACA,OACA,WACA,cAED,+BACD,cACA,QACA,OACA,WACA,cAEA,oBAAoB,WAAW,aAAa,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyC7C,qBACd,cACA,SAAS,cACT,QAAQ,aAAa,eACrB,kBAAkB,WAAW,UAC7B,sBAEA,SAAS,oCACP,cACA,QACA,OACA,WACA,cAED,oCACD,cACA,QACA,OACA,WACA,cAEA,oBAAoB,WAAW,aAAa,eAAe"}
@@ -0,0 +1,8 @@
//#region src/infiniteQueryOptions.ts
function infiniteQueryOptions(options) {
return options;
}
//#endregion
export { infiniteQueryOptions };
//# sourceMappingURL=infiniteQueryOptions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"infiniteQueryOptions.js","names":[],"sources":["../../src/infiniteQueryOptions.ts"],"sourcesContent":["import type {\n DefaultError,\n InfiniteData,\n InitialDataFunction,\n NonUndefinedGuard,\n OmitKeyof,\n QueryKey,\n QueryKeyWithDataTag,\n SkipToken,\n} from '@tanstack/query-core'\nimport type { UseInfiniteQueryOptions } from './types'\n\n/**\n * The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set — `data`\n * may be `undefined` while the query is `pending`.\n *\n * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,\n * the shape of all fetched pages plus their page params.\n * @template TQueryKey - The type of your `queryKey`.\n * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.\n */\nexport type UndefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> = UseInfiniteQueryOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n> & {\n /**\n * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been\n * created or cached yet). If set to a function, the function will be called **once** during the shared/root\n * query initialization, and be expected to synchronously return the initial data. Initial data is\n * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the\n * cache.\n */\n initialData?:\n | undefined\n | NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>\n | InitialDataFunction<\n NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>\n >\n}\n\n/**\n * The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set and\n * `queryFn` is not `skipToken` — same as {@link UndefinedInitialDataInfiniteOptions}, but `queryFn` may not be\n * `skipToken`.\n *\n * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,\n * the shape of all fetched pages plus their page params.\n * @template TQueryKey - The type of your `queryKey`.\n * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.\n */\nexport type UnusedSkipTokenInfiniteOptions<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> = OmitKeyof<\n UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>,\n 'queryFn'\n> & {\n /**\n * `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If\n * you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a\n * fetch that fails with \"Missing queryFn\" unless `enabled` is `false` or a default query function has been\n * defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own.\n */\n queryFn?: Exclude<\n UseInfiniteQueryOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >['queryFn'],\n SkipToken | undefined\n >\n}\n\n/**\n * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is set — `data` is\n * never `undefined`.\n *\n * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,\n * the shape of all fetched pages plus their page params.\n * @template TQueryKey - The type of your `queryKey`.\n * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.\n */\nexport type DefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> = UseInfiniteQueryOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n> & {\n /**\n * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been\n * created or cached yet). If set to a function, the function will be called **once** during the shared/root\n * query initialization, and be expected to synchronously return the initial data. Initial data is\n * considered stale by default unless a Line truncated
@@ -0,0 +1,9 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
//#region src/mutationOptions.ts
function mutationOptions(options) {
return options;
}
//#endregion
exports.mutationOptions = mutationOptions;
//# sourceMappingURL=mutationOptions.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"mutationOptions.cjs","names":[],"sources":["../../src/mutationOptions.ts"],"sourcesContent":["import type { DefaultError, WithRequired } from '@tanstack/query-core'\nimport type { UseMutationOptions } from './types'\n\n/**\n * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A\n * `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with\n * `useMutationState`.\n *\n * @see {@link useMutation} to run the mutation these options describe.\n * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a\n * required `mutationKey`.\n * @returns The same options object, unchanged.\n *\n * @example\n * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global \"saving…\" indicator:\n * ```tsx\n * import { mutationOptions, useMutationState } from '@tanstack/react-query'\n *\n * const createPostOptions = mutationOptions({\n * mutationKey: ['posts', 'create'],\n * mutationFn: createPost,\n * })\n *\n * function SavingIndicator() {\n * const isCreatingPost = useMutationState({\n * filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' },\n * }).length > 0\n *\n * return isCreatingPost ? <span>Saving…</span> : null\n * }\n * ```\n */\nexport function mutationOptions<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: WithRequired<\n UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n >,\n): WithRequired<\n UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n>\n/**\n * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No\n * `mutationKey` is required on this overload — use this when you don't need to target the mutation via a\n * `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters,\n * such as `status`.\n *\n * @see {@link useMutation} to run the mutation these options describe.\n * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a\n * `mutationKey`.\n * @returns The same options object, unchanged.\n * @remarks See the other overload's example for looking a mutation up via `useMutationState`.\n *\n * @example\n * ```tsx\n * import { mutationOptions, useMutation } from '@tanstack/react-query'\n *\n * export const createPostOptions = mutationOptions({\n * mutationFn: createPost,\n * })\n *\n * function CreatePost() {\n * const mutation = useMutation(createPostOptions)\n * return <button onClick={() => mutation.mutate({ title: 'Hello' })}>Create</button>\n * }\n * ```\n */\nexport function mutationOptions<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: Omit<\n UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n >,\n): Omit<\n UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n>\nexport function mutationOptions<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n): UseMutationOptions<TData, TError, TVariables, TOnMutateResult> {\n return options\n}\n"],"mappings":";;AAsFA,SAAgB,gBAMd,SACgE;CAChE,OAAO;AACT"}
@@ -0,0 +1,63 @@
import { UseMutationOptions } from "./types.cjs";
import { DefaultError, WithRequired } from "@tanstack/query-core";
//#region src/mutationOptions.d.ts
/**
* You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A
* `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with
* `useMutationState`.
*
* @see {@link useMutation} to run the mutation these options describe.
* @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a
* required `mutationKey`.
* @returns The same options object, unchanged.
*
* @example
* Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator:
* ```tsx
* import { mutationOptions, useMutationState } from '@tanstack/react-query'
*
* const createPostOptions = mutationOptions({
* mutationKey: ['posts', 'create'],
* mutationFn: createPost,
* })
*
* function SavingIndicator() {
* const isCreatingPost = useMutationState({
* filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' },
* }).length > 0
*
* return isCreatingPost ? <span>Saving…</span> : null
* }
* ```
*/
declare function mutationOptions<TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown>(options: WithRequired<UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, 'mutationKey'>): WithRequired<UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, 'mutationKey'>;
/**
* You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No
* `mutationKey` is required on this overload — use this when you don't need to target the mutation via a
* `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters,
* such as `status`.
*
* @see {@link useMutation} to run the mutation these options describe.
* @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a
* `mutationKey`.
* @returns The same options object, unchanged.
* @remarks See the other overload's example for looking a mutation up via `useMutationState`.
*
* @example
* ```tsx
* import { mutationOptions, useMutation } from '@tanstack/react-query'
*
* export const createPostOptions = mutationOptions({
* mutationFn: createPost,
* })
*
* function CreatePost() {
* const mutation = useMutation(createPostOptions)
* return <button onClick={() => mutation.mutate({ title: 'Hello' })}>Create</button>
* }
* ```
*/
declare function mutationOptions<TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown>(options: Omit<UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, 'mutationKey'>): Omit<UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, 'mutationKey'>;
//#endregion
export { mutationOptions };
//# sourceMappingURL=mutationOptions.d.cts.map
@@ -0,0 +1 @@
{"version":3,"file":"mutationOptions.d.cts","names":[],"sources":["../../src/mutationOptions.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgCgB,gBACd,iBACA,SAAS,cACT,mBACA,2BAEA,SAAS,aACP,mBAAmB,OAAO,QAAQ,YAAY,mCAG/C,aACD,mBAAmB,OAAO,QAAQ,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6BhC,gBACd,iBACA,SAAS,cACT,mBACA,2BAEA,SAAS,KACP,mBAAmB,OAAO,QAAQ,YAAY,mCAG/C,KACD,mBAAmB,OAAO,QAAQ,YAAY"}
@@ -0,0 +1,63 @@
import { UseMutationOptions } from "./types.js";
import { DefaultError, WithRequired } from "@tanstack/query-core";
//#region src/mutationOptions.d.ts
/**
* You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A
* `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with
* `useMutationState`.
*
* @see {@link useMutation} to run the mutation these options describe.
* @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a
* required `mutationKey`.
* @returns The same options object, unchanged.
*
* @example
* Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator:
* ```tsx
* import { mutationOptions, useMutationState } from '@tanstack/react-query'
*
* const createPostOptions = mutationOptions({
* mutationKey: ['posts', 'create'],
* mutationFn: createPost,
* })
*
* function SavingIndicator() {
* const isCreatingPost = useMutationState({
* filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' },
* }).length > 0
*
* return isCreatingPost ? <span>Saving…</span> : null
* }
* ```
*/
declare function mutationOptions<TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown>(options: WithRequired<UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, 'mutationKey'>): WithRequired<UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, 'mutationKey'>;
/**
* You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No
* `mutationKey` is required on this overload — use this when you don't need to target the mutation via a
* `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters,
* such as `status`.
*
* @see {@link useMutation} to run the mutation these options describe.
* @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a
* `mutationKey`.
* @returns The same options object, unchanged.
* @remarks See the other overload's example for looking a mutation up via `useMutationState`.
*
* @example
* ```tsx
* import { mutationOptions, useMutation } from '@tanstack/react-query'
*
* export const createPostOptions = mutationOptions({
* mutationFn: createPost,
* })
*
* function CreatePost() {
* const mutation = useMutation(createPostOptions)
* return <button onClick={() => mutation.mutate({ title: 'Hello' })}>Create</button>
* }
* ```
*/
declare function mutationOptions<TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown>(options: Omit<UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, 'mutationKey'>): Omit<UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, 'mutationKey'>;
//#endregion
export { mutationOptions };
//# sourceMappingURL=mutationOptions.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"mutationOptions.d.ts","names":[],"sources":["../../src/mutationOptions.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgCgB,gBACd,iBACA,SAAS,cACT,mBACA,2BAEA,SAAS,aACP,mBAAmB,OAAO,QAAQ,YAAY,mCAG/C,aACD,mBAAmB,OAAO,QAAQ,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6BhC,gBACd,iBACA,SAAS,cACT,mBACA,2BAEA,SAAS,KACP,mBAAmB,OAAO,QAAQ,YAAY,mCAG/C,KACD,mBAAmB,OAAO,QAAQ,YAAY"}
@@ -0,0 +1,8 @@
//#region src/mutationOptions.ts
function mutationOptions(options) {
return options;
}
//#endregion
export { mutationOptions };
//# sourceMappingURL=mutationOptions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"mutationOptions.js","names":[],"sources":["../../src/mutationOptions.ts"],"sourcesContent":["import type { DefaultError, WithRequired } from '@tanstack/query-core'\nimport type { UseMutationOptions } from './types'\n\n/**\n * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A\n * `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with\n * `useMutationState`.\n *\n * @see {@link useMutation} to run the mutation these options describe.\n * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a\n * required `mutationKey`.\n * @returns The same options object, unchanged.\n *\n * @example\n * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global \"saving…\" indicator:\n * ```tsx\n * import { mutationOptions, useMutationState } from '@tanstack/react-query'\n *\n * const createPostOptions = mutationOptions({\n * mutationKey: ['posts', 'create'],\n * mutationFn: createPost,\n * })\n *\n * function SavingIndicator() {\n * const isCreatingPost = useMutationState({\n * filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' },\n * }).length > 0\n *\n * return isCreatingPost ? <span>Saving…</span> : null\n * }\n * ```\n */\nexport function mutationOptions<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: WithRequired<\n UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n >,\n): WithRequired<\n UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n>\n/**\n * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No\n * `mutationKey` is required on this overload — use this when you don't need to target the mutation via a\n * `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters,\n * such as `status`.\n *\n * @see {@link useMutation} to run the mutation these options describe.\n * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a\n * `mutationKey`.\n * @returns The same options object, unchanged.\n * @remarks See the other overload's example for looking a mutation up via `useMutationState`.\n *\n * @example\n * ```tsx\n * import { mutationOptions, useMutation } from '@tanstack/react-query'\n *\n * export const createPostOptions = mutationOptions({\n * mutationFn: createPost,\n * })\n *\n * function CreatePost() {\n * const mutation = useMutation(createPostOptions)\n * return <button onClick={() => mutation.mutate({ title: 'Hello' })}>Create</button>\n * }\n * ```\n */\nexport function mutationOptions<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: Omit<\n UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n >,\n): Omit<\n UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n>\nexport function mutationOptions<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n): UseMutationOptions<TData, TError, TVariables, TOnMutateResult> {\n return options\n}\n"],"mappings":";AAsFA,SAAgB,gBAMd,SACgE;CAChE,OAAO;AACT"}
+9
View File
@@ -0,0 +1,9 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
//#region src/queryOptions.ts
function queryOptions(options) {
return options;
}
//#endregion
exports.queryOptions = queryOptions;
//# sourceMappingURL=queryOptions.cjs.map
@@ -0,0 +1 @@
{"version":3,"file":"queryOptions.cjs","names":[],"sources":["../../src/queryOptions.ts"],"sourcesContent":["import type {\n DefaultError,\n InitialDataFunction,\n NonUndefinedGuard,\n OmitKeyof,\n QueryFunction,\n QueryKey,\n QueryKeyWithDataTag,\n SkipToken,\n} from '@tanstack/query-core'\nimport type { UseQueryOptions } from './types'\n\n/**\n * The options accepted by the `queryOptions` overload selected when no `initialData` is set — `data` may be\n * `undefined` while the query is `pending`.\n *\n * @template TQueryFnData - The type your `queryFn` resolves to.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs.\n * @template TQueryKey - The type of your `queryKey`.\n */\nexport type UndefinedInitialDataOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = UseQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {\n /**\n * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been\n * created or cached yet). If set to a function, the function will be called **once** during the shared/root\n * query initialization, and be expected to synchronously return the initial data. Initial data is\n * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the\n * cache.\n */\n initialData?:\n | undefined\n | InitialDataFunction<NonUndefinedGuard<TQueryFnData>>\n | NonUndefinedGuard<TQueryFnData>\n}\n\n/**\n * The options accepted by the `queryOptions` overload selected when no `initialData` is set and `queryFn` is\n * not `skipToken` — same as {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.\n *\n * @template TQueryFnData - The type your `queryFn` resolves to.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs.\n * @template TQueryKey - The type of your `queryKey`.\n */\nexport type UnusedSkipTokenOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'queryFn'\n> & {\n /**\n * `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If\n * you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a\n * fetch that fails with \"Missing queryFn\" unless `enabled` is `false` or a default query function has been\n * defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own.\n */\n queryFn?: Exclude<\n UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'],\n SkipToken | undefined\n >\n}\n\n/**\n * The options accepted by the `queryOptions` overload selected when `initialData` is set — `data` is never\n * `undefined`.\n *\n * @template TQueryFnData - The type your `queryFn` resolves to.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs.\n * @template TQueryKey - The type of your `queryKey`.\n */\nexport type DefinedInitialDataOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = Omit<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'queryFn'> & {\n /**\n * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been\n * created or cached yet). If set to a function, the function will be called **once** during the shared/root\n * query initialization, and be expected to synchronously return the initial data. Initial data is\n * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the\n * cache.\n */\n initialData:\n | NonUndefinedGuard<TQueryFnData>\n | (() => NonUndefinedGuard<TQueryFnData>)\n /**\n * Optional here, but omitting it is only safe when no fetch will be attempted — for example with\n * `enabled: false`, or when a default query function has been defined. Otherwise, an enabled query with no\n * `queryFn` still tries to fetch and fails with a \"Missing queryFn\" error; `initialData` does not prevent this.\n */\n queryFn?: QueryFunction<TQueryFnData, TQueryKey>\n}\n\n/**\n * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can\n * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and\n * is the query key to generate options for.\n *\n * This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`.\n *\n * @see {@link useQuery} to run a query with these options.\n * @seeLine truncated
+194
View File
@@ -0,0 +1,194 @@
import { UseQueryOptions } from "./types.cjs";
import { DefaultError, InitialDataFunction, NonUndefinedGuard, OmitKeyof, QueryFunction, QueryKey, QueryKeyWithDataTag, SkipToken } from "@tanstack/query-core";
//#region src/queryOptions.d.ts
/**
* The options accepted by the `queryOptions` overload selected when no `initialData` is set — `data` may be
* `undefined` while the query is `pending`.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs.
* @template TQueryKey - The type of your `queryKey`.
*/
type UndefinedInitialDataOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = UseQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
/**
* If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
* created or cached yet). If set to a function, the function will be called **once** during the shared/root
* query initialization, and be expected to synchronously return the initial data. Initial data is
* considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
* cache.
*/
initialData?: undefined | InitialDataFunction<NonUndefinedGuard<TQueryFnData>> | NonUndefinedGuard<TQueryFnData>;
};
/**
* The options accepted by the `queryOptions` overload selected when no `initialData` is set and `queryFn` is
* not `skipToken` — same as {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs.
* @template TQueryKey - The type of your `queryKey`.
*/
type UnusedSkipTokenOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = OmitKeyof<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'queryFn'> & {
/**
* `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If
* you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a
* fetch that fails with "Missing queryFn" unless `enabled` is `false` or a default query function has been
* defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own.
*/
queryFn?: Exclude<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'], SkipToken | undefined>;
};
/**
* The options accepted by the `queryOptions` overload selected when `initialData` is set — `data` is never
* `undefined`.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs.
* @template TQueryKey - The type of your `queryKey`.
*/
type DefinedInitialDataOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = Omit<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'queryFn'> & {
/**
* If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
* created or cached yet). If set to a function, the function will be called **once** during the shared/root
* query initialization, and be expected to synchronously return the initial data. Initial data is
* considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
* cache.
*/
initialData: NonUndefinedGuard<TQueryFnData> | (() => NonUndefinedGuard<TQueryFnData>);
/**
* Optional here, but omitting it is only safe when no fetch will be attempted — for example with
* `enabled: false`, or when a default query function has been defined. Otherwise, an enabled query with no
* `queryFn` still tries to fetch and fails with a "Missing queryFn" error; `initialData` does not prevent this.
*/
queryFn?: QueryFunction<TQueryFnData, TQueryKey>;
};
/**
* You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
* be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
* is the query key to generate options for.
*
* This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`.
*
* @see {@link useQuery} to run a query with these options.
* @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
* @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` set.
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
*
* @example
* ```tsx
* import { queryOptions, useQuery } from '@tanstack/react-query'
*
* export const postsOptions = queryOptions({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* initialData: [],
* })
*
* function Posts() {
* // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails,
* // so the list stays visible alongside the error.
* const { data, isError, error } = useQuery(postsOptions)
*
* return (
* <div>
* {isError ? <span>Error: {error.message}</span> : null}
* <ul>
* {data.map((post) => <li key={post.id}>{post.title}</li>)}
* </ul>
* </div>
* )
* }
* ```
*/
declare function queryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>): DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
/**
* You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
* be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
* is the query key to generate options for.
*
* @see {@link useQuery} to run a query with these options.
* @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
* @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `useQuery`.
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
*
* @example
* A parameterized factory, so the same options object can be reused per `id`:
* ```tsx
* import { queryOptions, useQuery } from '@tanstack/react-query'
*
* export const postOptions = (id: string) =>
* queryOptions({
* queryKey: ['post', id],
* queryFn: () => fetchPost(id),
* })
*
* function Post({ id }: { id: string }) {
* const { data, isPending, isError, error } = useQuery(postOptions(id))
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return <h1>{data.title}</h1>
* }
* ```
*/
declare function queryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey>): UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey> & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
/**
* You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
* be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
* is the query key to generate options for.
*
* @see {@link useQuery} to run a query with these options.
* @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
* @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`.
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
* @remarks This is the only overload that accepts `queryFn: skipToken`, shown below.
*
* @example
* A parameterized factory, so the same options object can be reused per `id`:
* ```tsx
* import { queryOptions, useQuery } from '@tanstack/react-query'
*
* export const postOptions = (id: string) =>
* queryOptions({
* queryKey: ['post', id],
* queryFn: () => fetchPost(id),
* })
*
* function Post({ id }: { id: string }) {
* const { data, isPending, isError, error } = useQuery(postOptions(id))
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return <h1>{data.title}</h1>
* }
* ```
*
* @example
* A factory that disables the query, type safe, until `postId` is set:
* ```tsx
* import { queryOptions, skipToken, useQuery } from '@tanstack/react-query'
*
* export const postOptions = (postId: number | undefined) =>
* queryOptions({
* queryKey: ['post', postId],
* queryFn: postId != null ? () => fetchPost(postId) : skipToken,
* })
*
* function Post({ postId }: { postId: number | undefined }) {
* const { data, isLoading, isError, error } = useQuery(postOptions(postId))
*
* if (postId == null) return 'Select a post'
* if (isLoading) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return <h1>{data?.title}</h1>
* }
* ```
*/
declare function queryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>): UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
//#endregion
export { DefinedInitialDataOptions, UndefinedInitialDataOptions, UnusedSkipTokenOptions, queryOptions };
//# sourceMappingURL=queryOptions.d.cts.map
@@ -0,0 +1 @@
{"version":3,"file":"queryOptions.d.cts","names":[],"sources":["../../src/queryOptions.ts"],"mappings":";;;;;;;;;;;;KAqBY,4BACV,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,YAC3B,gBAAgB,cAAc,QAAQ,OAAO;;;;;;;;EAQ/C,0BAEI,oBAAoB,kBAAkB,iBACtC,kBAAkB;;;;;;;;;;;KAYZ,uBACV,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,YAC3B,UACF,gBAAgB,cAAc,QAAQ,OAAO;;;;;;;EAS7C,UAAU,QACR,gBAAgB,cAAc,QAAQ,OAAO,uBAC7C;;;;;;;;;;;KAaQ,0BACV,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,YAC3B,KAAK,gBAAgB,cAAc,QAAQ,OAAO;;;;;;;;EAQpD,aACI,kBAAkB,uBACX,kBAAkB;;;;;;EAM7B,UAAU,cAAc,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyCxB,aACd,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,UAE7B,SAAS,0BAA0B,cAAc,QAAQ,OAAO,aAC/D,0BAA0B,cAAc,QAAQ,OAAO,aACxD,oBAAoB,WAAW,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiC/B,aACd,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,UAE7B,SAAS,uBAAuB,cAAc,QAAQ,OAAO,aAC5D,uBAAuB,cAAc,QAAQ,OAAO,aACrD,oBAAoB,WAAW,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAwD/B,aACd,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,UAE7B,SAAS,4BAA4B,cAAc,QAAQ,OAAO,aACjE,4BAA4B,cAAc,QAAQ,OAAO,aAC1D,oBAAoB,WAAW,cAAc"}
+194
View File
@@ -0,0 +1,194 @@
import { UseQueryOptions } from "./types.js";
import { DefaultError, InitialDataFunction, NonUndefinedGuard, OmitKeyof, QueryFunction, QueryKey, QueryKeyWithDataTag, SkipToken } from "@tanstack/query-core";
//#region src/queryOptions.d.ts
/**
* The options accepted by the `queryOptions` overload selected when no `initialData` is set — `data` may be
* `undefined` while the query is `pending`.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs.
* @template TQueryKey - The type of your `queryKey`.
*/
type UndefinedInitialDataOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = UseQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
/**
* If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
* created or cached yet). If set to a function, the function will be called **once** during the shared/root
* query initialization, and be expected to synchronously return the initial data. Initial data is
* considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
* cache.
*/
initialData?: undefined | InitialDataFunction<NonUndefinedGuard<TQueryFnData>> | NonUndefinedGuard<TQueryFnData>;
};
/**
* The options accepted by the `queryOptions` overload selected when no `initialData` is set and `queryFn` is
* not `skipToken` — same as {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs.
* @template TQueryKey - The type of your `queryKey`.
*/
type UnusedSkipTokenOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = OmitKeyof<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'queryFn'> & {
/**
* `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If
* you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a
* fetch that fails with "Missing queryFn" unless `enabled` is `false` or a default query function has been
* defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own.
*/
queryFn?: Exclude<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'], SkipToken | undefined>;
};
/**
* The options accepted by the `queryOptions` overload selected when `initialData` is set — `data` is never
* `undefined`.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs.
* @template TQueryKey - The type of your `queryKey`.
*/
type DefinedInitialDataOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = Omit<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'queryFn'> & {
/**
* If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
* created or cached yet). If set to a function, the function will be called **once** during the shared/root
* query initialization, and be expected to synchronously return the initial data. Initial data is
* considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
* cache.
*/
initialData: NonUndefinedGuard<TQueryFnData> | (() => NonUndefinedGuard<TQueryFnData>);
/**
* Optional here, but omitting it is only safe when no fetch will be attempted — for example with
* `enabled: false`, or when a default query function has been defined. Otherwise, an enabled query with no
* `queryFn` still tries to fetch and fails with a "Missing queryFn" error; `initialData` does not prevent this.
*/
queryFn?: QueryFunction<TQueryFnData, TQueryKey>;
};
/**
* You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
* be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
* is the query key to generate options for.
*
* This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`.
*
* @see {@link useQuery} to run a query with these options.
* @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
* @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` set.
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
*
* @example
* ```tsx
* import { queryOptions, useQuery } from '@tanstack/react-query'
*
* export const postsOptions = queryOptions({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* initialData: [],
* })
*
* function Posts() {
* // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails,
* // so the list stays visible alongside the error.
* const { data, isError, error } = useQuery(postsOptions)
*
* return (
* <div>
* {isError ? <span>Error: {error.message}</span> : null}
* <ul>
* {data.map((post) => <li key={post.id}>{post.title}</li>)}
* </ul>
* </div>
* )
* }
* ```
*/
declare function queryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>): DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
/**
* You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
* be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
* is the query key to generate options for.
*
* @see {@link useQuery} to run a query with these options.
* @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
* @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `useQuery`.
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
*
* @example
* A parameterized factory, so the same options object can be reused per `id`:
* ```tsx
* import { queryOptions, useQuery } from '@tanstack/react-query'
*
* export const postOptions = (id: string) =>
* queryOptions({
* queryKey: ['post', id],
* queryFn: () => fetchPost(id),
* })
*
* function Post({ id }: { id: string }) {
* const { data, isPending, isError, error } = useQuery(postOptions(id))
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return <h1>{data.title}</h1>
* }
* ```
*/
declare function queryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey>): UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey> & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
/**
* You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
* be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
* is the query key to generate options for.
*
* @see {@link useQuery} to run a query with these options.
* @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
* @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`.
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
* @remarks This is the only overload that accepts `queryFn: skipToken`, shown below.
*
* @example
* A parameterized factory, so the same options object can be reused per `id`:
* ```tsx
* import { queryOptions, useQuery } from '@tanstack/react-query'
*
* export const postOptions = (id: string) =>
* queryOptions({
* queryKey: ['post', id],
* queryFn: () => fetchPost(id),
* })
*
* function Post({ id }: { id: string }) {
* const { data, isPending, isError, error } = useQuery(postOptions(id))
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return <h1>{data.title}</h1>
* }
* ```
*
* @example
* A factory that disables the query, type safe, until `postId` is set:
* ```tsx
* import { queryOptions, skipToken, useQuery } from '@tanstack/react-query'
*
* export const postOptions = (postId: number | undefined) =>
* queryOptions({
* queryKey: ['post', postId],
* queryFn: postId != null ? () => fetchPost(postId) : skipToken,
* })
*
* function Post({ postId }: { postId: number | undefined }) {
* const { data, isLoading, isError, error } = useQuery(postOptions(postId))
*
* if (postId == null) return 'Select a post'
* if (isLoading) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return <h1>{data?.title}</h1>
* }
* ```
*/
declare function queryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>): UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
//#endregion
export { DefinedInitialDataOptions, UndefinedInitialDataOptions, UnusedSkipTokenOptions, queryOptions };
//# sourceMappingURL=queryOptions.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"queryOptions.d.ts","names":[],"sources":["../../src/queryOptions.ts"],"mappings":";;;;;;;;;;;;KAqBY,4BACV,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,YAC3B,gBAAgB,cAAc,QAAQ,OAAO;;;;;;;;EAQ/C,0BAEI,oBAAoB,kBAAkB,iBACtC,kBAAkB;;;;;;;;;;;KAYZ,uBACV,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,YAC3B,UACF,gBAAgB,cAAc,QAAQ,OAAO;;;;;;;EAS7C,UAAU,QACR,gBAAgB,cAAc,QAAQ,OAAO,uBAC7C;;;;;;;;;;;KAaQ,0BACV,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,YAC3B,KAAK,gBAAgB,cAAc,QAAQ,OAAO;;;;;;;;EAQpD,aACI,kBAAkB,uBACX,kBAAkB;;;;;;EAM7B,UAAU,cAAc,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyCxB,aACd,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,UAE7B,SAAS,0BAA0B,cAAc,QAAQ,OAAO,aAC/D,0BAA0B,cAAc,QAAQ,OAAO,aACxD,oBAAoB,WAAW,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiC/B,aACd,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,UAE7B,SAAS,uBAAuB,cAAc,QAAQ,OAAO,aAC5D,uBAAuB,cAAc,QAAQ,OAAO,aACrD,oBAAoB,WAAW,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAwD/B,aACd,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,UAE7B,SAAS,4BAA4B,cAAc,QAAQ,OAAO,aACjE,4BAA4B,cAAc,QAAQ,OAAO,aAC1D,oBAAoB,WAAW,cAAc"}
+8
View File
@@ -0,0 +1,8 @@
//#region src/queryOptions.ts
function queryOptions(options) {
return options;
}
//#endregion
export { queryOptions };
//# sourceMappingURL=queryOptions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"queryOptions.js","names":[],"sources":["../../src/queryOptions.ts"],"sourcesContent":["import type {\n DefaultError,\n InitialDataFunction,\n NonUndefinedGuard,\n OmitKeyof,\n QueryFunction,\n QueryKey,\n QueryKeyWithDataTag,\n SkipToken,\n} from '@tanstack/query-core'\nimport type { UseQueryOptions } from './types'\n\n/**\n * The options accepted by the `queryOptions` overload selected when no `initialData` is set — `data` may be\n * `undefined` while the query is `pending`.\n *\n * @template TQueryFnData - The type your `queryFn` resolves to.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs.\n * @template TQueryKey - The type of your `queryKey`.\n */\nexport type UndefinedInitialDataOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = UseQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {\n /**\n * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been\n * created or cached yet). If set to a function, the function will be called **once** during the shared/root\n * query initialization, and be expected to synchronously return the initial data. Initial data is\n * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the\n * cache.\n */\n initialData?:\n | undefined\n | InitialDataFunction<NonUndefinedGuard<TQueryFnData>>\n | NonUndefinedGuard<TQueryFnData>\n}\n\n/**\n * The options accepted by the `queryOptions` overload selected when no `initialData` is set and `queryFn` is\n * not `skipToken` — same as {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.\n *\n * @template TQueryFnData - The type your `queryFn` resolves to.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs.\n * @template TQueryKey - The type of your `queryKey`.\n */\nexport type UnusedSkipTokenOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'queryFn'\n> & {\n /**\n * `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If\n * you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a\n * fetch that fails with \"Missing queryFn\" unless `enabled` is `false` or a default query function has been\n * defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own.\n */\n queryFn?: Exclude<\n UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'],\n SkipToken | undefined\n >\n}\n\n/**\n * The options accepted by the `queryOptions` overload selected when `initialData` is set — `data` is never\n * `undefined`.\n *\n * @template TQueryFnData - The type your `queryFn` resolves to.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs.\n * @template TQueryKey - The type of your `queryKey`.\n */\nexport type DefinedInitialDataOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = Omit<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'queryFn'> & {\n /**\n * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been\n * created or cached yet). If set to a function, the function will be called **once** during the shared/root\n * query initialization, and be expected to synchronously return the initial data. Initial data is\n * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the\n * cache.\n */\n initialData:\n | NonUndefinedGuard<TQueryFnData>\n | (() => NonUndefinedGuard<TQueryFnData>)\n /**\n * Optional here, but omitting it is only safe when no fetch will be attempted — for example with\n * `enabled: false`, or when a default query function has been defined. Otherwise, an enabled query with no\n * `queryFn` still tries to fetch and fails with a \"Missing queryFn\" error; `initialData` does not prevent this.\n */\n queryFn?: QueryFunction<TQueryFnData, TQueryKey>\n}\n\n/**\n * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can\n * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and\n * is the query key to generate options for.\n *\n * This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`.\n *\n * @see {@link useQuery} to run a query with these options.\n * @see Line truncated
@@ -0,0 +1,28 @@
//#region \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
Object.defineProperty(exports, "__toESM", {
enumerable: true,
get: function() {
return __toESM;
}
});
+23
View File
@@ -0,0 +1,23 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
//#region src/suspense.ts
const defaultThrowOnError = (_error, query) => query.state.data === void 0;
const ensureSuspenseTimers = (defaultedOptions) => {
if (defaultedOptions.suspense) {
const MIN_SUSPENSE_TIME_MS = 1e3;
const clamp = (value) => value === "static" ? value : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS);
const originalStaleTime = defaultedOptions.staleTime;
defaultedOptions.staleTime = typeof originalStaleTime === "function" ? (...args) => clamp(originalStaleTime(...args)) : clamp(originalStaleTime);
if (typeof defaultedOptions.gcTime === "number") defaultedOptions.gcTime = Math.max(defaultedOptions.gcTime, MIN_SUSPENSE_TIME_MS);
}
};
const shouldSuspend = (defaultedOptions, result) => (defaultedOptions === null || defaultedOptions === void 0 ? void 0 : defaultedOptions.suspense) && result.isPending;
const fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).catch(() => {
errorResetBoundary.clearReset();
});
//#endregion
exports.defaultThrowOnError = defaultThrowOnError;
exports.ensureSuspenseTimers = ensureSuspenseTimers;
exports.fetchOptimistic = fetchOptimistic;
exports.shouldSuspend = shouldSuspend;
//# sourceMappingURL=suspense.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"suspense.cjs","names":[],"sources":["../../src/suspense.ts"],"sourcesContent":["import type {\n DefaultError,\n DefaultedQueryObserverOptions,\n Query,\n QueryKey,\n QueryObserver,\n QueryObserverResult,\n} from '@tanstack/query-core'\nimport type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'\n\nexport const defaultThrowOnError = <\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n _error: TError,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n) => query.state.data === undefined\n\nexport const ensureSuspenseTimers = (\n defaultedOptions: DefaultedQueryObserverOptions<any, any, any, any, any>,\n) => {\n if (defaultedOptions.suspense) {\n // Handle staleTime to ensure minimum 1000ms in Suspense mode\n // This prevents unnecessary refetching when components remount after suspending\n const MIN_SUSPENSE_TIME_MS = 1000\n\n const clamp = (value: number | 'static' | undefined) =>\n value === 'static'\n ? value\n : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS)\n\n const originalStaleTime = defaultedOptions.staleTime\n defaultedOptions.staleTime =\n typeof originalStaleTime === 'function'\n ? (...args) => clamp(originalStaleTime(...args))\n : clamp(originalStaleTime)\n\n if (typeof defaultedOptions.gcTime === 'number') {\n defaultedOptions.gcTime = Math.max(\n defaultedOptions.gcTime,\n MIN_SUSPENSE_TIME_MS,\n )\n }\n }\n}\n\nexport const shouldSuspend = (\n defaultedOptions:\n | DefaultedQueryObserverOptions<any, any, any, any, any>\n | undefined,\n result: QueryObserverResult<any, any>,\n) => defaultedOptions?.suspense && result.isPending\n\nexport const fetchOptimistic = <\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey extends QueryKey,\n>(\n defaultedOptions: DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n observer: QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>,\n errorResetBoundary: QueryErrorResetBoundaryValue,\n) =>\n observer.fetchOptimistic(defaultedOptions).catch(() => {\n errorResetBoundary.clearReset()\n })\n"],"mappings":";;AAUA,MAAa,uBAMX,QACA,UACG,MAAM,MAAM,SAAS,KAAA;AAE1B,MAAa,wBACX,qBACG;CACH,IAAI,iBAAiB,UAAU;EAG7B,MAAM,uBAAuB;EAE7B,MAAM,SAAS,UACb,UAAU,WACN,QACA,KAAK,IAAI,SAAS,sBAAsB,oBAAoB;EAElE,MAAM,oBAAoB,iBAAiB;EAC3C,iBAAiB,YACf,OAAO,sBAAsB,cACxB,GAAG,SAAS,MAAM,kBAAkB,GAAG,IAAI,CAAC,IAC7C,MAAM,iBAAiB;EAE7B,IAAI,OAAO,iBAAiB,WAAW,UACrC,iBAAiB,SAAS,KAAK,IAC7B,iBAAiB,QACjB,oBACF;CAEJ;AACF;AAEA,MAAa,iBACX,kBAGA,YAAA,qBAAA,QAAA,qBAAA,KAAA,IAAA,KAAA,IACG,iBAAkB,aAAY,OAAO;AAE1C,MAAa,mBAOX,kBAOA,UACA,uBAEA,SAAS,gBAAgB,gBAAgB,CAAC,CAAC,YAAY;CACrD,mBAAmB,WAAW;AAChC,CAAC"}
+10
View File
@@ -0,0 +1,10 @@
import { QueryErrorResetBoundaryValue } from "./QueryErrorResetBoundary.cjs";
import { DefaultError, DefaultedQueryObserverOptions, Query, QueryKey, QueryObserver, QueryObserverResult } from "@tanstack/query-core";
//#region src/suspense.d.ts
declare const defaultThrowOnError: <TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(_error: TError, query: Query<TQueryFnData, TError, TData, TQueryKey>) => boolean;
declare const ensureSuspenseTimers: (defaultedOptions: DefaultedQueryObserverOptions<any, any, any, any, any>) => void;
declare const shouldSuspend: (defaultedOptions: DefaultedQueryObserverOptions<any, any, any, any, any> | undefined, result: QueryObserverResult<any, any>) => boolean | undefined;
declare const fetchOptimistic: <TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey>(defaultedOptions: DefaultedQueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>, observer: QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>, errorResetBoundary: QueryErrorResetBoundaryValue) => Promise<void | QueryObserverResult<TData, TError>>;
//#endregion
export { defaultThrowOnError, ensureSuspenseTimers, fetchOptimistic, shouldSuspend };
//# sourceMappingURL=suspense.d.cts.map
@@ -0,0 +1 @@
{"version":3,"file":"suspense.d.cts","names":[],"sources":["../../src/suspense.ts"],"mappings":";;;cAUa,sBACX,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,UAE7B,QAAQ,QACR,OAAO,MAAM,cAAc,QAAQ,OAAO;cAG/B,uBACX,kBAAkB;cA2BP,gBACX,kBACI,oEAEJ,QAAQ;cAGG,kBACX,cACA,QACA,OACA,YACA,kBAAkB,UAElB,kBAAkB,8BAChB,cACA,QACA,OACA,YACA,YAEF,UAAU,cAAc,cAAc,QAAQ,OAAO,YAAY,YACjE,oBAAoB,iCAA4B,eAAA,oBAAA,OAAA"}
+10
View File
@@ -0,0 +1,10 @@
import { QueryErrorResetBoundaryValue } from "./QueryErrorResetBoundary.js";
import { DefaultError, DefaultedQueryObserverOptions, Query, QueryKey, QueryObserver, QueryObserverResult } from "@tanstack/query-core";
//#region src/suspense.d.ts
declare const defaultThrowOnError: <TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(_error: TError, query: Query<TQueryFnData, TError, TData, TQueryKey>) => boolean;
declare const ensureSuspenseTimers: (defaultedOptions: DefaultedQueryObserverOptions<any, any, any, any, any>) => void;
declare const shouldSuspend: (defaultedOptions: DefaultedQueryObserverOptions<any, any, any, any, any> | undefined, result: QueryObserverResult<any, any>) => boolean | undefined;
declare const fetchOptimistic: <TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey>(defaultedOptions: DefaultedQueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>, observer: QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>, errorResetBoundary: QueryErrorResetBoundaryValue) => Promise<void | QueryObserverResult<TData, TError>>;
//#endregion
export { defaultThrowOnError, ensureSuspenseTimers, fetchOptimistic, shouldSuspend };
//# sourceMappingURL=suspense.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"suspense.d.ts","names":[],"sources":["../../src/suspense.ts"],"mappings":";;;cAUa,sBACX,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,UAE7B,QAAQ,QACR,OAAO,MAAM,cAAc,QAAQ,OAAO;cAG/B,uBACX,kBAAkB;cA2BP,gBACX,kBACI,oEAEJ,QAAQ;cAGG,kBACX,cACA,QACA,OACA,YACA,kBAAkB,UAElB,kBAAkB,8BAChB,cACA,QACA,OACA,YACA,YAEF,UAAU,cAAc,cAAc,QAAQ,OAAO,YAAY,YACjE,oBAAoB,iCAA4B,eAAA,oBAAA,OAAA"}
+19
View File
@@ -0,0 +1,19 @@
//#region src/suspense.ts
const defaultThrowOnError = (_error, query) => query.state.data === void 0;
const ensureSuspenseTimers = (defaultedOptions) => {
if (defaultedOptions.suspense) {
const MIN_SUSPENSE_TIME_MS = 1e3;
const clamp = (value) => value === "static" ? value : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS);
const originalStaleTime = defaultedOptions.staleTime;
defaultedOptions.staleTime = typeof originalStaleTime === "function" ? (...args) => clamp(originalStaleTime(...args)) : clamp(originalStaleTime);
if (typeof defaultedOptions.gcTime === "number") defaultedOptions.gcTime = Math.max(defaultedOptions.gcTime, MIN_SUSPENSE_TIME_MS);
}
};
const shouldSuspend = (defaultedOptions, result) => (defaultedOptions === null || defaultedOptions === void 0 ? void 0 : defaultedOptions.suspense) && result.isPending;
const fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).catch(() => {
errorResetBoundary.clearReset();
});
//#endregion
export { defaultThrowOnError, ensureSuspenseTimers, fetchOptimistic, shouldSuspend };
//# sourceMappingURL=suspense.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"suspense.js","names":[],"sources":["../../src/suspense.ts"],"sourcesContent":["import type {\n DefaultError,\n DefaultedQueryObserverOptions,\n Query,\n QueryKey,\n QueryObserver,\n QueryObserverResult,\n} from '@tanstack/query-core'\nimport type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'\n\nexport const defaultThrowOnError = <\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n _error: TError,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n) => query.state.data === undefined\n\nexport const ensureSuspenseTimers = (\n defaultedOptions: DefaultedQueryObserverOptions<any, any, any, any, any>,\n) => {\n if (defaultedOptions.suspense) {\n // Handle staleTime to ensure minimum 1000ms in Suspense mode\n // This prevents unnecessary refetching when components remount after suspending\n const MIN_SUSPENSE_TIME_MS = 1000\n\n const clamp = (value: number | 'static' | undefined) =>\n value === 'static'\n ? value\n : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS)\n\n const originalStaleTime = defaultedOptions.staleTime\n defaultedOptions.staleTime =\n typeof originalStaleTime === 'function'\n ? (...args) => clamp(originalStaleTime(...args))\n : clamp(originalStaleTime)\n\n if (typeof defaultedOptions.gcTime === 'number') {\n defaultedOptions.gcTime = Math.max(\n defaultedOptions.gcTime,\n MIN_SUSPENSE_TIME_MS,\n )\n }\n }\n}\n\nexport const shouldSuspend = (\n defaultedOptions:\n | DefaultedQueryObserverOptions<any, any, any, any, any>\n | undefined,\n result: QueryObserverResult<any, any>,\n) => defaultedOptions?.suspense && result.isPending\n\nexport const fetchOptimistic = <\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey extends QueryKey,\n>(\n defaultedOptions: DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n observer: QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>,\n errorResetBoundary: QueryErrorResetBoundaryValue,\n) =>\n observer.fetchOptimistic(defaultedOptions).catch(() => {\n errorResetBoundary.clearReset()\n })\n"],"mappings":";AAUA,MAAa,uBAMX,QACA,UACG,MAAM,MAAM,SAAS,KAAA;AAE1B,MAAa,wBACX,qBACG;CACH,IAAI,iBAAiB,UAAU;EAG7B,MAAM,uBAAuB;EAE7B,MAAM,SAAS,UACb,UAAU,WACN,QACA,KAAK,IAAI,SAAS,sBAAsB,oBAAoB;EAElE,MAAM,oBAAoB,iBAAiB;EAC3C,iBAAiB,YACf,OAAO,sBAAsB,cACxB,GAAG,SAAS,MAAM,kBAAkB,GAAG,IAAI,CAAC,IAC7C,MAAM,iBAAiB;EAE7B,IAAI,OAAO,iBAAiB,WAAW,UACrC,iBAAiB,SAAS,KAAK,IAC7B,iBAAiB,QACjB,oBACF;CAEJ;AACF;AAEA,MAAa,iBACX,kBAGA,YAAA,qBAAA,QAAA,qBAAA,KAAA,IAAA,KAAA,IACG,iBAAkB,aAAY,OAAO;AAE1C,MAAa,mBAOX,kBAOA,UACA,uBAEA,SAAS,gBAAgB,gBAAgB,CAAC,CAAC,YAAY;CACrD,mBAAmB,WAAW;AAChC,CAAC"}
+5
View File
@@ -0,0 +1,5 @@
//#region src/types.ts
/* istanbul ignore file */
//#endregion
//# sourceMappingURL=types.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"types.cjs","names":[],"sources":["../../src/types.ts"],"sourcesContent":["/* istanbul ignore file */\n\nimport type {\n DefaultError,\n DefinedInfiniteQueryObserverResult,\n DefinedQueryObserverResult,\n DistributiveOmit,\n InfiniteData,\n InfiniteQueryExecuteOptions,\n InfiniteQueryObserverOptions,\n InfiniteQueryObserverResult,\n MutateFunction,\n MutationObserverOptions,\n MutationObserverResult,\n OmitKeyof,\n Override,\n QueryExecuteOptions,\n QueryKey,\n QueryObserverOptions,\n QueryObserverResult,\n SkipToken,\n} from '@tanstack/query-core'\n\n/**\n * {@link UseBaseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't\n * relevant, e.g. when accepting options for any query in a helper function.\n */\nexport type AnyUseBaseQueryOptions = UseBaseQueryOptions<\n any,\n any,\n any,\n any,\n any\n>\n/**\n * The options shared by `useQuery` and `useSuspenseQuery`. Extends {@link QueryObserverOptions} from\n * `@tanstack/query-core` with the `react-query`-specific `subscribed` option.\n *\n * @template TQueryFnData - The type your `queryFn` resolves to.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no\n * `select` is used.\n * @template TQueryData - The type of the data actually held in the query cache — the input to `select` and\n * `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`.\n * @template TQueryKey - The type of your `queryKey`.\n */\nexport interface UseBaseQueryOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n> {\n /**\n * Set this to `false` to unsubscribe this observer from updates to the query cache.\n *\n * @defaultValue true\n */\n subscribed?: boolean\n}\n\n/**\n * The options accepted by `usePrefetchQuery` — everything you can pass to `queryClient.query`, except `queryFn`\n * is required unless a default query function has been defined.\n *\n * @template TQueryFnData - The type your `queryFn` resolves to.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no\n * `select` is used.\n * @template TQueryData - The type of the data actually held in the query cache — the input to `select` and\n * `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`.\n * @template TQueryKey - The type of your `queryKey`.\n */\nexport type UsePrefetchQueryOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = DistributiveOmit<\n QueryExecuteOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>,\n 'queryFn'\n> & {\n /**\n * `skipToken` is not allowed as a value here — a prefetch always needs a query function to actually run,\n * unless a default query function has been defined.\n */\n queryFn?: Exclude<\n QueryExecuteOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >['queryFn'],\n SkipToken\n >\n}\n\n/**\n * The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `queryClient.infiniteQuery`,\n * except `queryFn` is required unless a default query function has been defined.\n *\n * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs. Defaults to `InfiniteData<TQueryFnData>`,\n * the shape of all fetched pages plus their page params — a prefetch never reads `data` back out, so this\n * parameter only matters if you reuse these options elsewhere with `select` applied.\n * @template TQueryKey - The type of your `queryKey`.\n * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.\n */\nexport type UsePrefetchInfiniteQueryOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> = DistributiveOmit<\n InfiniteQueryExecuteOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n 'queryFn'\n> & {\n /**\n * `skipToken` is not allowed as a value here — a prefetch always needs a query function to actually run,\n * unless a default query function has been defined.\n */\n queryFn?: Exclude<\n InfiniteQueryExecuteOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >['queryFn'],\n SkipToken\n >\n}\n\n/**\n * {@link UseQueLine truncated
+280
View File
@@ -0,0 +1,280 @@
import { DefaultError, DefinedInfiniteQueryObserverResult, DefinedQueryObserverResult, DistributiveOmit, InfiniteData, InfiniteQueryExecuteOptions, InfiniteQueryObserverOptions, InfiniteQueryObserverResult, MutateFunction, MutationObserverOptions, MutationObserverResult, OmitKeyof, Override, QueryExecuteOptions, QueryKey, QueryObserverOptions, QueryObserverResult, SkipToken } from "@tanstack/query-core";
//#region src/types.d.ts
/**
* {@link UseBaseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't
* relevant, e.g. when accepting options for any query in a helper function.
*/
type AnyUseBaseQueryOptions = UseBaseQueryOptions<any, any, any, any, any>;
/**
* The options shared by `useQuery` and `useSuspenseQuery`. Extends {@link QueryObserverOptions} from
* `@tanstack/query-core` with the `react-query`-specific `subscribed` option.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no
* `select` is used.
* @template TQueryData - The type of the data actually held in the query cache — the input to `select` and
* `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`.
* @template TQueryKey - The type of your `queryKey`.
*/
interface UseBaseQueryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> extends QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey> {
/**
* Set this to `false` to unsubscribe this observer from updates to the query cache.
*
* @defaultValue true
*/
subscribed?: boolean;
}
/**
* The options accepted by `usePrefetchQuery` — everything you can pass to `queryClient.query`, except `queryFn`
* is required unless a default query function has been defined.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no
* `select` is used.
* @template TQueryData - The type of the data actually held in the query cache — the input to `select` and
* `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`.
* @template TQueryKey - The type of your `queryKey`.
*/
type UsePrefetchQueryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = DistributiveOmit<QueryExecuteOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>, 'queryFn'> & {
/**
* `skipToken` is not allowed as a value here — a prefetch always needs a query function to actually run,
* unless a default query function has been defined.
*/
queryFn?: Exclude<QueryExecuteOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>['queryFn'], SkipToken>;
};
/**
* The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `queryClient.infiniteQuery`,
* except `queryFn` is required unless a default query function has been defined.
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs. Defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params — a prefetch never reads `data` back out, so this
* parameter only matters if you reuse these options elsewhere with `select` applied.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
type UsePrefetchInfiniteQueryOptions<TQueryFnData = unknown, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> = DistributiveOmit<InfiniteQueryExecuteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, 'queryFn'> & {
/**
* `skipToken` is not allowed as a value here — a prefetch always needs a query function to actually run,
* unless a default query function has been defined.
*/
queryFn?: Exclude<InfiniteQueryExecuteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>['queryFn'], SkipToken>;
};
/**
* {@link UseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't
* relevant, e.g. when accepting options for any query in a helper function.
*/
type AnyUseQueryOptions = UseQueryOptions<any, any, any, any>;
/**
* The options accepted by `useQuery`. Same as {@link UseBaseQueryOptions}, minus `suspense` (which
* `react-query` derives from which hook you call rather than exposing as an option).
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no
* `select` is used.
* @template TQueryKey - The type of your `queryKey`.
*/
interface UseQueryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> extends OmitKeyof<UseBaseQueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey>, 'suspense'> {}
/**
* {@link UseSuspenseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't
* relevant, e.g. when accepting options for any query in a helper function.
*/
type AnyUseSuspenseQueryOptions = UseSuspenseQueryOptions<any, any, any, any>;
/**
* The options accepted by `useSuspenseQuery`. Same as {@link UseQueryOptions}, minus `enabled`, `throwOnError`,
* and `placeholderData` — Suspense hooks cannot render a "disabled" or "placeholder" state, so those options
* don't apply.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no
* `select` is used.
* @template TQueryKey - The type of your `queryKey`.
*/
interface UseSuspenseQueryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> extends OmitKeyof<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'queryFn' | 'enabled' | 'throwOnError' | 'placeholderData'> {
/**
* `skipToken` is not allowed here — Suspense hooks cannot render a "disabled" state, so a query function
* must always be provided, unless a default query function has been defined.
*/
queryFn?: Exclude<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'], SkipToken>;
}
/**
* {@link UseInfiniteQueryOptions} with all type parameters set to `any`, useful when the specific types aren't
* relevant, e.g. when accepting options for any query in a helper function.
*/
type AnyUseInfiniteQueryOptions = UseInfiniteQueryOptions<any, any, any, any, any>;
/**
* The options accepted by `useInfiniteQuery`. Extends {@link InfiniteQueryObserverOptions} from
* `@tanstack/query-core` with the `react-query`-specific `subscribed` option, minus `suspense` (which
* `react-query` derives from which hook you call rather than exposing as an option).
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
interface UseInfiniteQueryOptions<TQueryFnData = unknown, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> extends OmitKeyof<InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, 'suspense'> {
/**
* Set this to `false` to unsubscribe this observer from updates to the query cache.
*
* @defaultValue true
*/
subscribed?: boolean;
}
/**
* {@link UseSuspenseInfiniteQueryOptions} with all type parameters set to `any`, useful when the specific types
* aren't relevant, e.g. when accepting options for any query in a helper function.
*/
type AnyUseSuspenseInfiniteQueryOptions = UseSuspenseInfiniteQueryOptions<any, any, any, any, any>;
/**
* The options accepted by `useSuspenseInfiniteQuery`. Same as {@link UseInfiniteQueryOptions}, minus `enabled`,
* `throwOnError`, and `placeholderData` — Suspense hooks cannot render a "disabled" or "placeholder" state, so
* those options don't apply.
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
interface UseSuspenseInfiniteQueryOptions<TQueryFnData = unknown, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> extends OmitKeyof<UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, 'queryFn' | 'enabled' | 'throwOnError' | 'placeholderData'> {
/**
* `skipToken` is not allowed here — Suspense hooks cannot render a "disabled" state, so a query function
* must always be provided, unless a default query function has been defined.
*/
queryFn?: Exclude<UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>['queryFn'], SkipToken>;
}
/**
* The result of `useQuery` when `initialData` isn't set — `data` may be `undefined` while the query is
* `pending`. Re-exports {@link QueryObserverResult} from `@tanstack/query-core`. `useInfiniteQuery` returns
* {@link UseInfiniteQueryResult} instead.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
type UseBaseQueryResult<TData = unknown, TError = DefaultError> = QueryObserverResult<TData, TError>;
/**
* The result of `useQuery`. Same as {@link UseBaseQueryResult}.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
type UseQueryResult<TData = unknown, TError = DefaultError> = UseBaseQueryResult<TData, TError>;
/**
* The result of `useSuspenseQuery`. Same as {@link DefinedUseQueryResult}, minus `isPlaceholderData` — always
* `false` on that type, so this drops the dead field rather than an active state.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
type UseSuspenseQueryResult<TData = unknown, TError = DefaultError> = DistributiveOmit<DefinedQueryObserverResult<TData, TError>, 'isPlaceholderData'>;
/**
* The result of `useQuery` when `initialData` is set, or of `useSuspenseQuery` before the `isPlaceholderData`
* omission — `data` is never `undefined`. Re-exports {@link DefinedQueryObserverResult} from
* `@tanstack/query-core`.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
type DefinedUseQueryResult<TData = unknown, TError = DefaultError> = DefinedQueryObserverResult<TData, TError>;
/**
* The result of `useInfiniteQuery` when `initialData` isn't set — `data` may be `undefined` while the query is
* `pending`. Re-exports {@link InfiniteQueryObserverResult} from `@tanstack/query-core`.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
type UseInfiniteQueryResult<TData = unknown, TError = DefaultError> = InfiniteQueryObserverResult<TData, TError>;
/**
* The result of `useInfiniteQuery` when `initialData` is set — `data` is never `undefined`. Re-exports
* {@link DefinedInfiniteQueryObserverResult} from `@tanstack/query-core`.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
type DefinedUseInfiniteQueryResult<TData = unknown, TError = DefaultError> = DefinedInfiniteQueryObserverResult<TData, TError>;
/**
* The result of `useSuspenseInfiniteQuery`. Same as {@link DefinedUseInfiniteQueryResult}, minus
* `isPlaceholderData` — Suspense hooks never render placeholder data.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
type UseSuspenseInfiniteQueryResult<TData = unknown, TError = DefaultError> = OmitKeyof<DefinedInfiniteQueryObserverResult<TData, TError>, 'isPlaceholderData'>;
/**
* {@link UseMutationOptions} with all type parameters set to `any`, useful when the specific types aren't
* relevant, e.g. when accepting options for any mutation in a helper function.
*/
type AnyUseMutationOptions = UseMutationOptions<any, any, any, any>;
/**
* The options accepted by `useMutation`. Same as {@link MutationObserverOptions} from `@tanstack/query-core`,
* minus the internal `_defaulted` flag.
*
* @template TData - The type your mutation function resolves to.
* @template TError - The type of errors your mutation function may throw.
* @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`.
* @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
* their `onMutateResult` parameter — useful for optimistic-update rollback data.
*/
interface UseMutationOptions<TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown> extends OmitKeyof<MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>, '_defaulted'> {}
/**
* The type of `mutate`, as returned by `useMutation`. Forwards the variables (and an optional per-call
* `onSuccess`/`onError`/`onSettled`) to the underlying `mutate` call. Fire-and-forget — errors are surfaced
* through the mutation result, not thrown.
*
* @template TData - The type your mutation function resolves to.
* @template TError - The type of errors your mutation function may throw.
* @template TVariables - The type of the variable passed to `mutate`.
* @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
* their `onMutateResult` parameter — useful for optimistic-update rollback data.
*/
type UseMutateFunction<TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown> = (...args: Parameters<MutateFunction<TData, TError, TVariables, TOnMutateResult>>) => void;
/**
* The type of `mutateAsync`, as returned by `useMutation`. Similar to {@link UseMutateFunction}, but returns a
* promise which can be awaited.
*
* @template TData - The type your mutation function resolves to.
* @template TError - The type of errors your mutation function may throw.
* @template TVariables - The type of the variable passed to `mutateAsync`.
* @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
* their `onMutateResult` parameter — useful for optimistic-update rollback data.
*/
type UseMutateAsyncFunction<TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown> = MutateFunction<TData, TError, TVariables, TOnMutateResult>;
/**
* The result of `useMutation`. Same as {@link MutationObserverResult} from `@tanstack/query-core`, with
* `mutate` narrowed to the fire-and-forget {@link UseMutateFunction} signature, plus the added `mutateAsync`.
*
* @template TData - The type your mutation function resolves to.
* @template TError - The type of errors your mutation function may throw.
* @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`.
* @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
* their `onMutateResult` parameter — useful for optimistic-update rollback data.
*/
type UseBaseMutationResult<TData = unknown, TError = DefaultError, TVariables = unknown, TOnMutateResult = unknown> = Override<MutationObserverResult<TData, TError, TVariables, TOnMutateResult>, {
mutate: UseMutateFunction<TData, TError, TVariables, TOnMutateResult>;
}> & {
/**
* Similar to `mutate`, but returns a promise which can be awaited.
*/
mutateAsync: UseMutateAsyncFunction<TData, TError, TVariables, TOnMutateResult>;
};
/**
* The result of `useMutation`. Same as {@link UseBaseMutationResult}.
*
* @template TData - The type your mutation function resolves to.
* @template TError - The type of errors your mutation function may throw.
* @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`.
* @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
* their `onMutateResult` parameter — useful for optimistic-update rollback data.
*/
type UseMutationResult<TData = unknown, TError = DefaultError, TVariables = unknown, TOnMutateResult = unknown> = UseBaseMutationResult<TData, TError, TVariables, TOnMutateResult>;
//#endregion
export { AnyUseBaseQueryOptions, AnyUseInfiniteQueryOptions, AnyUseMutationOptions, AnyUseQueryOptions, AnyUseSuspenseInfiniteQueryOptions, AnyUseSuspenseQueryOptions, DefinedUseInfiniteQueryResult, DefinedUseQueryResult, UseBaseMutationResult, UseBaseQueryOptions, UseBaseQueryResult, UseInfiniteQueryOptions, UseInfiniteQueryResult, UseMutateAsyncFunction, UseMutateFunction, UseMutationOptions, UseMutationResult, UsePrefetchInfiniteQueryOptions, UsePrefetchQueryOptions, UseQueryOptions, UseQueryResult, UseSuspenseInfiniteQueryOptions, UseSuspenseInfiniteQueryResult, UseSuspenseQueryOptions, UseSuspenseQueryResult };
//# sourceMappingURL=types.d.cts.map
Loaded 100 of 4271 files, more files were not shown because too many files have changed in this diff. Show more