{"version":3,"file":"useMutationState.cjs","names":["useQueryClient","replaceEqualDeep","React","notifyManager"],"sources":["../../src/useMutationState.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nimport { notifyManager, replaceEqualDeep } from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n  Mutation,\n  MutationCache,\n  MutationFilters,\n  MutationState,\n  QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`\n * (useful for app-wide loading indicators).\n * @param filters - The {@link MutationFilters} to narrow down the matched mutations.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be the `number` of the mutations that your application currently has `pending`.\n * @example\n * ```tsx\n * import { useIsMutating } from '@tanstack/react-query'\n *\n * function PostsMutatingIndicator() {\n *   // How many mutations matching the posts prefix are in progress?\n *   const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })\n *\n *   return isMutatingPosts ? <span>Saving posts...</span> : null\n * }\n * ```\n */\nexport function useIsMutating(\n  filters?: MutationFilters,\n  queryClient?: QueryClient,\n): number {\n  const client = useQueryClient(queryClient)\n  return useMutationState(\n    { filters: { ...filters, status: 'pending' } },\n    client,\n  ).length\n}\n\ntype MutationTypeFromResult<TResult> = [TResult] extends [\n  MutationState<\n    infer TData,\n    infer TError,\n    infer TVariables,\n    infer TOnMutateResult\n  >,\n]\n  ? Mutation<TData, TError, TVariables, TOnMutateResult>\n  : Mutation\n\ntype MutationStateOptions<\n  TResult = MutationState,\n  TMutation extends Mutation<any, any, any, any> =\n    MutationTypeFromResult<TResult>,\n> = {\n  filters?: MutationFilters\n  select?: (mutation: TMutation) => TResult\n}\n\n/**\n * Creates snapshot getters that share equal selected results across renders.\n * A new getter is created on each render. Each getter caches its snapshot until the matching mutations\n * or their states change.\n * @returns A factory for snapshot getters with a shared result cache.\n */\nfunction createSnapshotFactory<\n  TResult = MutationState,\n  TMutation extends Mutation<any, any, any, any> =\n    MutationTypeFromResult<TResult>,\n>() {\n  let previousResult: Array<TResult> | undefined\n\n  return (\n    mutationCache: MutationCache,\n    options: MutationStateOptions<TResult, TMutation>,\n  ) => {\n    let inputs: Array<unknown> = []\n    let snapshot: Array<TResult> | undefined\n\n    return (): Array<TResult> => {\n      const mutations = mutationCache.findAll(options.filters)\n      const nextInputs = mutations.flatMap((mutation) => [\n        mutation,\n        mutation.state,\n      ])\n\n      if (\n        !snapshot ||\n        nextInputs.length !== inputs.length ||\n        nextInputs.some((input, index) => !Object.is(input, inputs[index]))\n      ) {\n        inputs = nextInputs\n        snapshot = replaceEqualDeep(\n          previousResult,\n          mutations.map(\n            (mutation): TResult =>\n              (options.select\n                ? options.select(mutation as TMutation)\n                : mutation.state) as TResult,\n          ),\n        )\n        previousResult = snapshot\n      }\n\n      return snapshot\n    }\n  }\n}\n\n/**\n * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass\n * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation\n * state.\n * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the\n * mutation state.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be an Array of whatever `select` returns for each matching mutation.\n * @example\n * Get all variables of all running mutations:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function PendingPosts() {\n *   const pendingVariables = useMutationState({\n *     filters: { status: 'pending' },\n *     select: (mutation) => mutation.state.variables,\n *   })\n *\n *   return <>{pendingVariables.length} posts saving...</>\n * }\n * ```\n * @example\n * Get all data for specific mutations via the `mutationKey`:\n * ```tsx\n * import { useMutation, useMutationState } from '@tanstack/react-query'\n *\n * const mutationKey = ['posts']\n *\n * function Posts() {\n *   // Some mutation that we want to get the state for\n *   const mutation = useMutation({\n *     mutationKey,\n *     mutationFn: createPosts,\n *   })\n *\n *   const savedPosts = useMutationState({\n *     // this mutation key needs to match the mutation key of the given mutation (see above)\n *     filters: { mutationKey, status: 'success' },\n *     select: (mutation) => mutation.state.data,\n *   })\n *\n *   return (\n *     <button onClick={() => mutation.mutate(['New Post'])}>\n *       Create post ({savedPosts.length} saved so far)\n *     </button>\n *   )\n * }\n * ```\n * @example\n * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new\n * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the\n * last item that `useMutationState` returns to get the latest successful invocation:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function LatestPost() {\n *   const savedPosts = useMutationState({\n *     filters: { mutationKey: ['posts'], status: 'success' },\n *     select: (mutation) => mutation.state.data,\n *   })\n *\n *   const latestSavedPost = savedPosts[savedPosts.length - 1]\n *\n *   return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>\n * }\n * ```\n */\nexport function useMutationState<\n  TResult = MutationState,\n  TMutation extends Mutation<any, any, any, any> =\n    MutationTypeFromResult<TResult>,\n>(\n  options: MutationStateOptions<TResult, TMutation> = {},\n  queryClient?: QueryClient,\n): Array<TResult> {\n  const mutationCache = useQueryClient(queryClient).getMutationCache()\n  const [createSnapshot] = React.useState(() =>\n    createSnapshotFactory<TResult, TMutation>(),\n  )\n  const getSnapshot = createSnapshot(mutationCache, options)\n\n  return React.useSyncExternalStore(\n    React.useCallback(\n      (onStoreChange) =>\n        mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)),\n      [mutationCache],\n    ),\n    getSnapshot,\n    getSnapshot,\n  )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,cACd,SACA,aACQ;CACR,MAAM,SAASA,4BAAAA,eAAe,WAAW;CACzC,OAAO,iBACL,EAAE,SAAS;EAAE,GAAG;EAAS,QAAQ;CAAU,EAAE,GAC7C,MACF,CAAC,CAAC;AACJ;;;;;;;AA4BA,SAAS,wBAIL;CACF,IAAI;CAEJ,QACE,eACA,YACG;EACH,IAAI,SAAyB,CAAC;EAC9B,IAAI;EAEJ,aAA6B;GAC3B,MAAM,YAAY,cAAc,QAAQ,QAAQ,OAAO;GACvD,MAAM,aAAa,UAAU,SAAS,aAAa,CACjD,UACA,SAAS,KACX,CAAC;GAED,IACE,CAAC,YACD,WAAW,WAAW,OAAO,UAC7B,WAAW,MAAM,OAAO,UAAU,CAAC,OAAO,GAAG,OAAO,OAAO,MAAM,CAAC,GAClE;IACA,SAAS;IACT,YAAA,GAAWC,qBAAAA,iBAAAA,CACT,gBACA,UAAU,KACP,aACE,QAAQ,SACL,QAAQ,OAAO,QAAqB,IACpC,SAAS,KACjB,CACF;IACA,iBAAiB;GACnB;GAEA,OAAO;EACT;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,SAAgB,iBAKd,UAAoD,CAAC,GACrD,aACgB;CAChB,MAAM,gBAAgBD,4BAAAA,eAAe,WAAW,CAAC,CAAC,iBAAiB;CACnE,MAAM,CAAC,kBAAkBE,MAAM,eAC7B,sBAA0C,CAC5C;CACA,MAAM,cAAc,eAAe,eAAe,OAAO;CAEzD,OAAOA,MAAM,qBACXA,MAAM,aACH,kBACC,cAAc,UAAUC,qBAAAA,cAAc,WAAW,aAAa,CAAC,GACjE,CAAC,aAAa,CAChB,GACA,aACA,WACF;AACF"}