;\ntype UseQuerySubscriptionOptions = SubscriptionOptions & {\n /**\n * Prevents a query from automatically running.\n *\n * @remarks\n * When `skip` is true (or `skipToken` is passed in as `arg`):\n *\n * - **If the query has cached data:**\n * * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed\n * * The query will have a status of `uninitialized`\n * * If `skip: false` is set after the initial load, the cached result will be used\n * - **If the query does not have cached data:**\n * * The query will have a status of `uninitialized`\n * * The query will not exist in the state when viewed with the dev tools\n * * The query will not automatically fetch on mount\n * * The query will not automatically run when additional components with the same query are added that do run\n *\n * @example\n * ```tsx\n * // codeblock-meta no-transpile title=\"Skip example\"\n * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n * const { data, error, status } = useGetPokemonByNameQuery(name, {\n * skip,\n * });\n *\n * return (\n * \n * {name} - {status}\n *
\n * );\n * };\n * ```\n */\n skip?: boolean;\n /**\n * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n *\n * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n */\n refetchOnMountOrArgChange?: boolean | number;\n};\n\n/**\n * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.\n *\n * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n */\nexport type UseQuerySubscription> = (arg: QueryArgFrom | SkipToken, options?: UseQuerySubscriptionOptions) => UseQuerySubscriptionResult;\nexport type TypedUseQuerySubscription = UseQuerySubscription>;\nexport type UseQuerySubscriptionResult> = Pick, 'refetch'>;\n\n/**\n * Helper type to manually type the result\n * of the `useQuerySubscription` hook in userland code.\n */\nexport type TypedUseQuerySubscriptionResult = UseQuerySubscriptionResult>;\nexport type UseLazyQueryLastPromiseInfo> = {\n lastArg: QueryArgFrom;\n};\n\n/**\n * A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.\n *\n * This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).\n *\n * #### Features\n *\n * - Manual control over firing a request to retrieve data\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once\n *\n * #### Note\n *\n * When the trigger function returned from a LazyQuery is called, it always initiates a new request to the server even if there is cached data. Set `preferCacheValue`(the second argument to the function) as `true` if you want it to immediately return a cached value if one exists.\n */\nexport type UseLazyQuery> = = UseQueryStateDefaultResult>(options?: SubscriptionOptions & Omit, 'skip'>) => [LazyQueryTrigger, UseQueryStateResult, UseLazyQueryLastPromiseInfo];\nexport type TypedUseLazyQuery = UseLazyQuery>;\nexport type LazyQueryTrigger> = {\n /**\n * Triggers a lazy query.\n *\n * By default, this will start a new request even if there is already a value in the cache.\n * If you want to use the cache value and only start a request if there is no cache value, set the second argument to `true`.\n *\n * @remarks\n * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().\n *\n * @example\n * ```ts\n * // codeblock-meta title=\"Using .unwrap with async await\"\n * try {\n * const payload = await getUserById(1).unwrap();\n * console.log('fulfilled', payload)\n * } catch (error) {\n * console.error('rejected', error);\n * }\n * ```\n */\n (arg: QueryArgFrom, preferCacheValue?: boolean): QueryActionCreatorResult;\n};\nexport type TypedLazyQueryTrigger = LazyQueryTrigger>;\n\n/**\n * A React hook similar to [`useQuerySubscription`](#usequerysubscription), but with manual control over when the data fetching occurs.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useLazyQuery`](#uselazyquery).\n *\n * #### Features\n *\n * - Manual control over firing a request to retrieve data\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once\n */\nexport type UseLazyQuerySubscription> = (options?: SubscriptionOptions) => readonly [LazyQueryTrigger, QueryArgFrom | UninitializedValue];\nexport type TypedUseLazyQuerySubscription = UseLazyQuerySubscription>;\n\n/**\n * @internal\n */\nexport type QueryStateSelector, D extends QueryDefinition> = (state: UseQueryStateDefaultResult) => R;\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryStateSelector} for use with a specific query.\n * This is useful for scenarios where you want to create a \"pre-typed\"\n * {@linkcode UseQueryStateOptions.selectFromResult | selectFromResult}\n * function.\n *\n * @example\n * #### __Create a strongly-typed `selectFromResult` selector function__\n *\n * ```tsx\n * import type { TypedQueryStateSelector } from '@reduxjs/toolkit/query/react'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n *\n * type Post = {\n * id: number\n * title: string\n * }\n *\n * type PostsApiResponse = {\n * posts: Post[]\n * total: number\n * skip: number\n * limit: number\n * }\n *\n * type QueryArgument = number | undefined\n *\n * type BaseQueryFunction = ReturnType\n *\n * type SelectedResult = Pick\n *\n * const postsApiSlice = createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),\n * reducerPath: 'postsApi',\n * tagTypes: ['Posts'],\n * endpoints: (build) => ({\n * getPosts: build.query({\n * query: (limit = 5) => `?limit=${limit}&select=title`,\n * }),\n * }),\n * })\n *\n * const { useGetPostsQuery } = postsApiSlice\n *\n * function PostById({ id }: { id: number }) {\n * const { post } = useGetPostsQuery(undefined, {\n * selectFromResult: (state) => ({\n * post: state.data?.posts.find((post) => post.id === id),\n * }),\n * })\n *\n * return {post?.title}\n * }\n *\n * const EMPTY_ARRAY: Post[] = []\n *\n * const typedSelectFromResult: TypedQueryStateSelector<\n * PostsApiResponse,\n * QueryArgument,\n * BaseQueryFunction,\n * SelectedResult\n * > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY })\n *\n * function PostsList() {\n * const { posts } = useGetPostsQuery(undefined, {\n * selectFromResult: typedSelectFromResult,\n * })\n *\n * return (\n * \n *
\n * {posts.map((post) => (\n * \n * ))}\n *
\n *
\n * )\n * }\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template SelectedResultType - The type of the selected result returned by the __`selectFromResult`__ function.\n *\n * @since 2.7.9\n * @public\n */\nexport type TypedQueryStateSelector = UseQueryStateDefaultResult>> = QueryStateSelector>;\n\n/**\n * A React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.\n *\n * Note that this hook does not trigger fetching new data. For that use-case, see [`useQuery`](#usequery) or [`useQuerySubscription`](#usequerysubscription).\n *\n * #### Features\n *\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport type UseQueryState> = = UseQueryStateDefaultResult>(arg: QueryArgFrom | SkipToken, options?: UseQueryStateOptions) => UseQueryStateResult;\nexport type TypedUseQueryState = UseQueryState>;\n\n/**\n * @internal\n */\nexport type UseQueryStateOptions, R extends Record> = {\n /**\n * Prevents a query from automatically running.\n *\n * @remarks\n * When skip is true:\n *\n * - **If the query has cached data:**\n * * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed\n * * The query will have a status of `uninitialized`\n * * If `skip: false` is set after skipping the initial load, the cached result will be used\n * - **If the query does not have cached data:**\n * * The query will have a status of `uninitialized`\n * * The query will not exist in the state when viewed with the dev tools\n * * The query will not automatically fetch on mount\n * * The query will not automatically run when additional components with the same query are added that do run\n *\n * @example\n * ```ts\n * // codeblock-meta title=\"Skip example\"\n * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n * const { data, error, status } = useGetPokemonByNameQuery(name, {\n * skip,\n * });\n *\n * return (\n * \n * {name} - {status}\n *
\n * );\n * };\n * ```\n */\n skip?: boolean;\n /**\n * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.\n * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.\n * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.\n *\n * @example\n * ```ts\n * // codeblock-meta title=\"Using selectFromResult to extract a single result\"\n * function PostsList() {\n * const { data: posts } = api.useGetPostsQuery();\n *\n * return (\n * \n * {posts?.data?.map((post) => (\n * \n * ))}\n *
\n * );\n * }\n *\n * function PostById({ id }: { id: number }) {\n * // Will select the post with the given id, and will only rerender if the given posts data changes\n * const { post } = api.useGetPostsQuery(undefined, {\n * selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),\n * });\n *\n * return {post?.name};\n * }\n * ```\n */\n selectFromResult?: QueryStateSelector;\n};\n\n/**\n * Provides a way to define a \"pre-typed\" version of\n * {@linkcode UseQueryStateOptions} with specific options for a given query.\n * This is particularly useful for setting default query behaviors such as\n * refetching strategies, which can be overridden as needed.\n *\n * @example\n * #### __Create a `useQuery` hook with default options__\n *\n * ```ts\n * import type {\n * SubscriptionOptions,\n * TypedUseQueryStateOptions,\n * } from '@reduxjs/toolkit/query/react'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n *\n * type Post = {\n * id: number\n * name: string\n * }\n *\n * const api = createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * tagTypes: ['Post'],\n * endpoints: (build) => ({\n * getPosts: build.query({\n * query: () => 'posts',\n * }),\n * }),\n * })\n *\n * const { useGetPostsQuery } = api\n *\n * export const useGetPostsQueryWithDefaults = <\n * SelectedResult extends Record,\n * >(\n * overrideOptions: TypedUseQueryStateOptions<\n * Post[],\n * void,\n * ReturnType,\n * SelectedResult\n * > &\n * SubscriptionOptions,\n * ) =>\n * useGetPostsQuery(undefined, {\n * // Insert default options here\n *\n * refetchOnMountOrArgChange: true,\n * refetchOnFocus: true,\n * ...overrideOptions,\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArg - The type of the argument passed into the query.\n * @template BaseQuery - The type of the base query function being used.\n * @template SelectedResult - The type of the selected result returned by the __`selectFromResult`__ function.\n *\n * @since 2.7.8\n * @public\n */\nexport type TypedUseQueryStateOptions = UseQueryStateDefaultResult>> = UseQueryStateOptions, SelectedResult>;\nexport type UseQueryStateResult<_ extends QueryDefinition, R> = TSHelpersNoInfer;\n\n/**\n * Helper type to manually type the result\n * of the `useQueryState` hook in userland code.\n */\nexport type TypedUseQueryStateResult>> = TSHelpersNoInfer;\ntype UseQueryStateBaseResult> = QuerySubState & {\n /**\n * Where `data` tries to hold data as much as possible, also re-using\n * data from the last arguments passed into the hook, this property\n * will always contain the received data from the query, for the current query arguments.\n */\n currentData?: ResultTypeFrom;\n /**\n * Query has not started yet.\n */\n isUninitialized: false;\n /**\n * Query is currently loading for the first time. No data yet.\n */\n isLoading: false;\n /**\n * Query is currently fetching, but might have data from an earlier request.\n */\n isFetching: false;\n /**\n * Query has data from a successful load.\n */\n isSuccess: false;\n /**\n * Query is currently in \"error\" state.\n */\n isError: false;\n};\ntype UseQueryStateDefaultResult> = TSHelpersId, {\n status: QueryStatus.uninitialized;\n}>, {\n isUninitialized: true;\n}> | TSHelpersOverride, {\n isLoading: true;\n isFetching: boolean;\n data: undefined;\n} | ({\n isSuccess: true;\n isFetching: true;\n error: undefined;\n} & Required, 'data' | 'fulfilledTimeStamp'>>) | ({\n isSuccess: true;\n isFetching: false;\n error: undefined;\n} & Required, 'data' | 'fulfilledTimeStamp' | 'currentData'>>) | ({\n isError: true;\n} & Required, 'error'>>)>> & {\n /**\n * @deprecated Included for completeness, but discouraged.\n * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`\n * and `isUninitialized` flags instead\n */\n status: QueryStatus;\n};\nexport type MutationStateSelector, D extends MutationDefinition> = (state: MutationResultSelectorResult) => R;\nexport type UseMutationStateOptions, R extends Record> = {\n selectFromResult?: MutationStateSelector;\n fixedCacheKey?: string;\n};\nexport type UseMutationStateResult, R> = TSHelpersNoInfer & {\n originalArgs?: QueryArgFrom;\n /**\n * Resets the hook state to its initial `uninitialized` state.\n * This will also remove the last result from the cache.\n */\n reset: () => void;\n};\n\n/**\n * Helper type to manually type the result\n * of the `useMutation` hook in userland code.\n */\nexport type TypedUseMutationResult>> = UseMutationStateResult, R>;\n\n/**\n * A React hook that lets you trigger an update request for a given endpoint, and subscribes the component to read the request status from the Redux store. The component will re-render as the loading status changes.\n *\n * #### Features\n *\n * - Manual control over firing a request to alter data on the server or possibly invalidate the cache\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport type UseMutation> = = MutationResultSelectorResult>(options?: UseMutationStateOptions) => readonly [MutationTrigger, UseMutationStateResult];\nexport type TypedUseMutation = UseMutation>;\nexport type MutationTrigger> = {\n /**\n * Triggers the mutation and returns a Promise.\n * @remarks\n * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\n *\n * @example\n * ```ts\n * // codeblock-meta title=\"Using .unwrap with async await\"\n * try {\n * const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\n * console.log('fulfilled', payload)\n * } catch (error) {\n * console.error('rejected', error);\n * }\n * ```\n */\n (arg: QueryArgFrom): MutationActionCreatorResult;\n};\nexport type TypedMutationTrigger = MutationTrigger>;\n\n/**\n * Wrapper around `defaultQueryStateSelector` to be used in `useQuery`.\n * We want the initial render to already come back with\n * `{ isUninitialized: false, isFetching: true, isLoading: true }`\n * to prevent that the library user has to do an additional check for `isUninitialized`/\n */\nconst noPendingQueryStateSelector: QueryStateSelector = selected => {\n if (selected.isUninitialized) {\n return ({\n ...selected,\n isUninitialized: false,\n isFetching: true,\n isLoading: selected.data !== undefined ? false : true,\n status: QueryStatus.pending\n } as any);\n }\n return selected;\n};\ntype GenericPrefetchThunk = (endpointName: any, arg: any, options: PrefetchOptions) => ThunkAction;\n\n/**\n *\n * @param opts.api - An API with defined endpoints to create hooks for\n * @param opts.moduleOptions.batch - The version of the `batchedUpdates` function to be used\n * @param opts.moduleOptions.useDispatch - The version of the `useDispatch` hook to be used\n * @param opts.moduleOptions.useSelector - The version of the `useSelector` hook to be used\n * @returns An object containing functions to generate hooks based on an endpoint\n */\nexport function buildHooks({\n api,\n moduleOptions: {\n batch,\n hooks: {\n useDispatch,\n useSelector,\n useStore\n },\n unstable__sideEffectsInRender,\n createSelector\n },\n serializeQueryArgs,\n context\n}: {\n api: Api;\n moduleOptions: Required;\n serializeQueryArgs: SerializeQueryArgs;\n context: ApiContext;\n}) {\n const usePossiblyImmediateEffect: (effect: () => void | undefined, deps?: DependencyList) => void = unstable__sideEffectsInRender ? cb => cb() : useEffect;\n return {\n buildQueryHooks,\n buildMutationHook,\n usePrefetch\n };\n function queryStatePreSelector(currentState: QueryResultSelectorResult, lastResult: UseQueryStateDefaultResult | undefined, queryArgs: any): UseQueryStateDefaultResult {\n // if we had a last result and the current result is uninitialized,\n // we might have called `api.util.resetApiState`\n // in this case, reset the hook\n if (lastResult?.endpointName && currentState.isUninitialized) {\n const {\n endpointName\n } = lastResult;\n const endpointDefinition = context.endpointDefinitions[endpointName];\n if (serializeQueryArgs({\n queryArgs: lastResult.originalArgs,\n endpointDefinition,\n endpointName\n }) === serializeQueryArgs({\n queryArgs,\n endpointDefinition,\n endpointName\n })) lastResult = undefined;\n }\n\n // data is the last known good request result we have tracked - or if none has been tracked yet the last good result for the current args\n let data = currentState.isSuccess ? currentState.data : lastResult?.data;\n if (data === undefined) data = currentState.data;\n const hasData = data !== undefined;\n\n // isFetching = true any time a request is in flight\n const isFetching = currentState.isLoading;\n // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)\n const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;\n // isSuccess = true when data is present\n const isSuccess = currentState.isSuccess || isFetching && hasData;\n return ({\n ...currentState,\n data,\n currentData: currentState.data,\n isFetching,\n isLoading,\n isSuccess\n } as UseQueryStateDefaultResult);\n }\n function usePrefetch>(endpointName: EndpointName, defaultOptions?: PrefetchOptions) {\n const dispatch = useDispatch>();\n const stableDefaultOptions = useShallowStableValue(defaultOptions);\n return useCallback((arg: any, options?: PrefetchOptions) => dispatch((api.util.prefetch as GenericPrefetchThunk)(endpointName, arg, {\n ...stableDefaultOptions,\n ...options\n })), [endpointName, dispatch, stableDefaultOptions]);\n }\n function buildQueryHooks(name: string): QueryHooks {\n const useQuerySubscription: UseQuerySubscription = (arg: any, {\n refetchOnReconnect,\n refetchOnFocus,\n refetchOnMountOrArgChange,\n skip = false,\n pollingInterval = 0,\n skipPollingIfUnfocused = false\n } = {}) => {\n const {\n initiate\n } = (api.endpoints[name] as ApiEndpointQuery, Definitions>);\n const dispatch = useDispatch>();\n\n // TODO: Change this to `useRef(undefined)` after upgrading to React 19.\n /**\n * @todo Change this to `useRef(undefined)` after upgrading to React 19.\n */\n const subscriptionSelectorsRef = useRef(undefined);\n if (!subscriptionSelectorsRef.current) {\n const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());\n if (process.env.NODE_ENV !== 'production') {\n if (typeof returnedValue !== 'object' || typeof returnedValue?.type === 'string') {\n throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(37) : `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\n You must add the middleware for RTK-Query to function correctly!`);\n }\n }\n subscriptionSelectorsRef.current = ((returnedValue as unknown) as SubscriptionSelectors);\n }\n const stableArg = useStableQueryArgs(skip ? skipToken : arg,\n // Even if the user provided a per-endpoint `serializeQueryArgs` with\n // a consistent return value, _here_ we want to use the default behavior\n // so we can tell if _anything_ actually changed. Otherwise, we can end up\n // with a case where the query args did change but the serialization doesn't,\n // and then we never try to initiate a refetch.\n defaultSerializeQueryArgs, context.endpointDefinitions[name], name);\n const stableSubscriptionOptions = useShallowStableValue({\n refetchOnReconnect,\n refetchOnFocus,\n pollingInterval,\n skipPollingIfUnfocused\n });\n const lastRenderHadSubscription = useRef(false);\n\n // TODO: Change this to `useRef>(undefined)` after upgrading to React 19.\n /**\n * @todo Change this to `useRef>(undefined)` after upgrading to React 19.\n */\n const promiseRef = useRef | undefined>(undefined);\n let {\n queryCacheKey,\n requestId\n } = promiseRef.current || {};\n\n // HACK We've saved the middleware subscription lookup callbacks into a ref,\n // so we can directly check here if the subscription exists for this query.\n let currentRenderHasSubscription = false;\n if (queryCacheKey && requestId) {\n currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(queryCacheKey, requestId);\n }\n const subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;\n usePossiblyImmediateEffect(() => {\n lastRenderHadSubscription.current = currentRenderHasSubscription;\n });\n usePossiblyImmediateEffect((): void | undefined => {\n if (subscriptionRemoved) {\n promiseRef.current = undefined;\n }\n }, [subscriptionRemoved]);\n usePossiblyImmediateEffect((): void | undefined => {\n const lastPromise = promiseRef.current;\n if (typeof process !== 'undefined' && process.env.NODE_ENV === 'removeMeOnCompilation') {\n // this is only present to enforce the rule of hooks to keep `isSubscribed` in the dependency array\n console.log(subscriptionRemoved);\n }\n if (stableArg === skipToken) {\n lastPromise?.unsubscribe();\n promiseRef.current = undefined;\n return;\n }\n const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;\n if (!lastPromise || lastPromise.arg !== stableArg) {\n lastPromise?.unsubscribe();\n const promise = dispatch(initiate(stableArg, {\n subscriptionOptions: stableSubscriptionOptions,\n forceRefetch: refetchOnMountOrArgChange\n }));\n promiseRef.current = promise;\n } else if (stableSubscriptionOptions !== lastSubscriptionOptions) {\n lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);\n }\n }, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved]);\n useEffect(() => {\n return () => {\n promiseRef.current?.unsubscribe();\n promiseRef.current = undefined;\n };\n }, []);\n return useMemo(() => ({\n /**\n * A method to manually refetch data for the query\n */\n refetch: () => {\n if (!promiseRef.current) throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(38) : 'Cannot refetch a query that has not been started yet.');\n return promiseRef.current?.refetch();\n }\n }), []);\n };\n const useLazyQuerySubscription: UseLazyQuerySubscription = ({\n refetchOnReconnect,\n refetchOnFocus,\n pollingInterval = 0,\n skipPollingIfUnfocused = false\n } = {}) => {\n const {\n initiate\n } = (api.endpoints[name] as ApiEndpointQuery, Definitions>);\n const dispatch = useDispatch>();\n const [arg, setArg] = useState(UNINITIALIZED_VALUE);\n\n // TODO: Change this to `useRef>(undefined)` after upgrading to React 19.\n /**\n * @todo Change this to `useRef>(undefined)` after upgrading to React 19.\n */\n const promiseRef = useRef | undefined>(undefined);\n const stableSubscriptionOptions = useShallowStableValue({\n refetchOnReconnect,\n refetchOnFocus,\n pollingInterval,\n skipPollingIfUnfocused\n });\n usePossiblyImmediateEffect(() => {\n const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;\n if (stableSubscriptionOptions !== lastSubscriptionOptions) {\n promiseRef.current?.updateSubscriptionOptions(stableSubscriptionOptions);\n }\n }, [stableSubscriptionOptions]);\n const subscriptionOptionsRef = useRef(stableSubscriptionOptions);\n usePossiblyImmediateEffect(() => {\n subscriptionOptionsRef.current = stableSubscriptionOptions;\n }, [stableSubscriptionOptions]);\n const trigger = useCallback(function (arg: any, preferCacheValue = false) {\n let promise: QueryActionCreatorResult;\n batch(() => {\n promiseRef.current?.unsubscribe();\n promiseRef.current = promise = dispatch(initiate(arg, {\n subscriptionOptions: subscriptionOptionsRef.current,\n forceRefetch: !preferCacheValue\n }));\n setArg(arg);\n });\n return promise!;\n }, [dispatch, initiate]);\n\n /* cleanup on unmount */\n useEffect(() => {\n return () => {\n promiseRef?.current?.unsubscribe();\n };\n }, []);\n\n /* if \"cleanup on unmount\" was triggered from a fast refresh, we want to reinstate the query */\n useEffect(() => {\n if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {\n trigger(arg, true);\n }\n }, [arg, trigger]);\n return useMemo(() => ([trigger, arg] as const), [trigger, arg]);\n };\n const useQueryState: UseQueryState = (arg: any, {\n skip = false,\n selectFromResult\n } = {}) => {\n const {\n select\n } = (api.endpoints[name] as ApiEndpointQuery, Definitions>);\n const stableArg = useStableQueryArgs(skip ? skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);\n type ApiRootState = Parameters>[0];\n const lastValue = useRef(undefined);\n const selectDefaultResult: Selector = useMemo(() => createSelector([select(stableArg), (_: ApiRootState, lastResult: any) => lastResult, (_: ApiRootState) => stableArg], queryStatePreSelector, {\n memoizeOptions: {\n resultEqualityCheck: shallowEqual\n }\n }), [select, stableArg]);\n const querySelector: Selector = useMemo(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult, {\n devModeChecks: {\n identityFunctionCheck: 'never'\n }\n }) : selectDefaultResult, [selectDefaultResult, selectFromResult]);\n const currentState = useSelector((state: RootState) => querySelector(state, lastValue.current), shallowEqual);\n const store = useStore>();\n const newLastValue = selectDefaultResult(store.getState(), lastValue.current);\n useIsomorphicLayoutEffect(() => {\n lastValue.current = newLastValue;\n }, [newLastValue]);\n return currentState;\n };\n return {\n useQueryState,\n useQuerySubscription,\n useLazyQuerySubscription,\n useLazyQuery(options) {\n const [trigger, arg] = useLazyQuerySubscription(options);\n const queryStateResults = useQueryState(arg, {\n ...options,\n skip: arg === UNINITIALIZED_VALUE\n });\n const info = useMemo(() => ({\n lastArg: arg\n }), [arg]);\n return useMemo(() => [trigger, queryStateResults, info], [trigger, queryStateResults, info]);\n },\n useQuery(arg, options) {\n const querySubscriptionResults = useQuerySubscription(arg, options);\n const queryStateResults = useQueryState(arg, {\n selectFromResult: arg === skipToken || options?.skip ? undefined : noPendingQueryStateSelector,\n ...options\n });\n const {\n data,\n status,\n isLoading,\n isSuccess,\n isError,\n error\n } = queryStateResults;\n useDebugValue({\n data,\n status,\n isLoading,\n isSuccess,\n isError,\n error\n });\n return useMemo(() => ({\n ...queryStateResults,\n ...querySubscriptionResults\n }), [queryStateResults, querySubscriptionResults]);\n }\n };\n }\n function buildMutationHook(name: string): UseMutation {\n return ({\n selectFromResult,\n fixedCacheKey\n } = {}) => {\n const {\n select,\n initiate\n } = (api.endpoints[name] as ApiEndpointMutation, Definitions>);\n const dispatch = useDispatch>();\n const [promise, setPromise] = useState>();\n useEffect(() => () => {\n if (!promise?.arg.fixedCacheKey) {\n promise?.reset();\n }\n }, [promise]);\n const triggerMutation = useCallback(function (arg: Parameters['0']) {\n const promise = dispatch(initiate(arg, {\n fixedCacheKey\n }));\n setPromise(promise);\n return promise;\n }, [dispatch, initiate, fixedCacheKey]);\n const {\n requestId\n } = promise || {};\n const selectDefaultResult = useMemo(() => select({\n fixedCacheKey,\n requestId: promise?.requestId\n }), [fixedCacheKey, promise, select]);\n const mutationSelector = useMemo((): Selector, any> => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]);\n const currentState = useSelector(mutationSelector, shallowEqual);\n const originalArgs = fixedCacheKey == null ? promise?.arg.originalArgs : undefined;\n const reset = useCallback(() => {\n batch(() => {\n if (promise) {\n setPromise(undefined);\n }\n if (fixedCacheKey) {\n dispatch(api.internalActions.removeMutationResult({\n requestId,\n fixedCacheKey\n }));\n }\n });\n }, [dispatch, fixedCacheKey, promise, requestId]);\n const {\n endpointName,\n data,\n status,\n isLoading,\n isSuccess,\n isError,\n error\n } = currentState;\n useDebugValue({\n endpointName,\n data,\n status,\n isLoading,\n isSuccess,\n isError,\n error\n });\n const finalState = useMemo(() => ({\n ...currentState,\n originalArgs,\n reset\n }), [currentState, originalArgs, reset]);\n return useMemo(() => ([triggerMutation, finalState] as const), [triggerMutation, finalState]);\n };\n }\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { Api, BaseQueryFn, EndpointDefinitions, Module, MutationDefinition, PrefetchOptions, QueryArgFrom, QueryDefinition, QueryKeys } from '@reduxjs/toolkit/query';\nimport { batch as rrBatch, useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore } from 'react-redux';\nimport { createSelector as _createSelector } from 'reselect';\nimport { isMutationDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { safeAssign } from '../tsHelpers';\nimport { capitalize, countObjectKeys } from '../utils';\nimport type { MutationHooks, QueryHooks } from './buildHooks';\nimport { buildHooks } from './buildHooks';\nimport type { HooksWithUniqueNames } from './namedHooks';\nexport const reactHooksModuleName = /* @__PURE__ */Symbol();\nexport type ReactHooksModule = typeof reactHooksModuleName;\ndeclare module '@reduxjs/toolkit/query' {\n export interface ApiModules<\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n ReducerPath extends string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n TagTypes extends string> {\n [reactHooksModuleName]: {\n /**\n * Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.\n */\n endpoints: { [K in keyof Definitions]: Definitions[K] extends QueryDefinition ? QueryHooks : Definitions[K] extends MutationDefinition ? MutationHooks : never };\n /**\n * A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.\n */\n usePrefetch>(endpointName: EndpointName, options?: PrefetchOptions): (arg: QueryArgFrom, options?: PrefetchOptions) => void;\n } & HooksWithUniqueNames;\n }\n}\ntype RR = typeof import('react-redux');\nexport interface ReactHooksModuleOptions {\n /**\n * The hooks from React Redux to be used\n */\n hooks?: {\n /**\n * The version of the `useDispatch` hook to be used\n */\n useDispatch: RR['useDispatch'];\n /**\n * The version of the `useSelector` hook to be used\n */\n useSelector: RR['useSelector'];\n /**\n * The version of the `useStore` hook to be used\n */\n useStore: RR['useStore'];\n };\n /**\n * The version of the `batchedUpdates` function to be used\n */\n batch?: RR['batch'];\n /**\n * Enables performing asynchronous tasks immediately within a render.\n *\n * @example\n *\n * ```ts\n * import {\n * buildCreateApi,\n * coreModule,\n * reactHooksModule\n * } from '@reduxjs/toolkit/query/react'\n *\n * const createApi = buildCreateApi(\n * coreModule(),\n * reactHooksModule({ unstable__sideEffectsInRender: true })\n * )\n * ```\n */\n unstable__sideEffectsInRender?: boolean;\n /**\n * A selector creator (usually from `reselect`, or matching the same signature)\n */\n createSelector?: typeof _createSelector;\n}\n\n/**\n * Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.\n *\n * @example\n * ```ts\n * const MyContext = React.createContext(null);\n * const customCreateApi = buildCreateApi(\n * coreModule(),\n * reactHooksModule({\n * hooks: {\n * useDispatch: createDispatchHook(MyContext),\n * useSelector: createSelectorHook(MyContext),\n * useStore: createStoreHook(MyContext)\n * }\n * })\n * );\n * ```\n *\n * @returns A module for use with `buildCreateApi`\n */\nexport const reactHooksModule = ({\n batch = rrBatch,\n hooks = {\n useDispatch: rrUseDispatch,\n useSelector: rrUseSelector,\n useStore: rrUseStore\n },\n createSelector = _createSelector,\n unstable__sideEffectsInRender = false,\n ...rest\n}: ReactHooksModuleOptions = {}): Module => {\n if (process.env.NODE_ENV !== 'production') {\n const hookNames = (['useDispatch', 'useSelector', 'useStore'] as const);\n let warned = false;\n for (const hookName of hookNames) {\n // warn for old hook options\n if (countObjectKeys(rest) > 0) {\n if ((rest as Partial)[hookName]) {\n if (!warned) {\n console.warn('As of RTK 2.0, the hooks now need to be specified as one object, provided under a `hooks` key:' + '\\n`reactHooksModule({ hooks: { useDispatch, useSelector, useStore } })`');\n warned = true;\n }\n }\n // migrate\n // @ts-ignore\n hooks[hookName] = rest[hookName];\n }\n // then make sure we have them all\n if (typeof hooks[hookName] !== 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(36) : `When using custom hooks for context, all ${hookNames.length} hooks need to be provided: ${hookNames.join(', ')}.\\nHook ${hookName} was either not provided or not a function.`);\n }\n }\n }\n return {\n name: reactHooksModuleName,\n init(api, {\n serializeQueryArgs\n }, context) {\n const anyApi = ((api as any) as Api, any, any, ReactHooksModule>);\n const {\n buildQueryHooks,\n buildMutationHook,\n usePrefetch\n } = buildHooks({\n api,\n moduleOptions: {\n batch,\n hooks,\n unstable__sideEffectsInRender,\n createSelector\n },\n serializeQueryArgs,\n context\n });\n safeAssign(anyApi, {\n usePrefetch\n });\n safeAssign(context, {\n batch\n });\n return {\n injectEndpoint(endpointName, definition) {\n if (isQueryDefinition(definition)) {\n const {\n useQuery,\n useLazyQuery,\n useLazyQuerySubscription,\n useQueryState,\n useQuerySubscription\n } = buildQueryHooks(endpointName);\n safeAssign(anyApi.endpoints[endpointName], {\n useQuery,\n useLazyQuery,\n useLazyQuerySubscription,\n useQueryState,\n useQuerySubscription\n });\n (api as any)[`use${capitalize(endpointName)}Query`] = useQuery;\n (api as any)[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;\n } else if (isMutationDefinition(definition)) {\n const useMutation = buildMutationHook(endpointName);\n safeAssign(anyApi.endpoints[endpointName], {\n useMutation\n });\n (api as any)[`use${capitalize(endpointName)}Mutation`] = useMutation;\n }\n }\n };\n }\n };\n};","// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nimport { buildCreateApi, coreModule } from '@reduxjs/toolkit/query';\nimport { reactHooksModule, reactHooksModuleName } from './module';\nexport * from '@reduxjs/toolkit/query';\nexport { ApiProvider } from './ApiProvider';\nconst createApi = /* @__PURE__ */buildCreateApi(coreModule(), reactHooksModule());\nexport type { TypedUseMutationResult, TypedUseQueryHookResult, TypedUseQueryStateResult, TypedUseQuerySubscriptionResult, TypedLazyQueryTrigger, TypedUseLazyQuery, TypedUseMutation, TypedMutationTrigger, TypedQueryStateSelector, TypedUseQueryState, TypedUseQuery, TypedUseQuerySubscription, TypedUseLazyQuerySubscription, TypedUseQueryStateOptions } from './buildHooks';\nexport { UNINITIALIZED_VALUE } from './constants';\nexport { createApi, reactHooksModule, reactHooksModuleName };","import type { Api } from '@reduxjs/toolkit/query';\nimport type { BaseQueryApi, BaseQueryArg, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta, BaseQueryResult, QueryReturnValue } from './baseQueryTypes';\nimport type { QuerySubState, RootState } from './core';\nimport type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection';\nimport type { CacheLifecycleMutationExtraOptions, CacheLifecycleQueryExtraOptions } from './core/buildMiddleware/cacheLifecycle';\nimport type { QueryLifecycleMutationExtraOptions, QueryLifecycleQueryExtraOptions } from './core/buildMiddleware/queryLifecycle';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { NEVER } from './fakeBaseQuery';\nimport type { CastAny, HasRequiredProps, MaybePromise, NonUndefined, OmitFromUnion, UnwrapPromise } from './tsHelpers';\nconst resultType = /* @__PURE__ */Symbol();\nconst baseQuery = /* @__PURE__ */Symbol();\ntype EndpointDefinitionWithQuery = {\n /**\n * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"query example\"\n *\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n * interface Post {\n * id: number\n * name: string\n * }\n * type PostsResponse = Post[]\n *\n * const api = createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * tagTypes: ['Post'],\n * endpoints: (build) => ({\n * getPosts: build.query({\n * // highlight-start\n * query: () => 'posts',\n * // highlight-end\n * }),\n * addPost: build.mutation>({\n * // highlight-start\n * query: (body) => ({\n * url: `posts`,\n * method: 'POST',\n * body,\n * }),\n * // highlight-end\n * invalidatesTags: [{ type: 'Post', id: 'LIST' }],\n * }),\n * })\n * })\n * ```\n */\n query(arg: QueryArg): BaseQueryArg;\n queryFn?: never;\n /**\n * A function to manipulate the data returned by a query or mutation.\n */\n transformResponse?(baseQueryReturnValue: BaseQueryResult, meta: BaseQueryMeta, arg: QueryArg): ResultType | Promise;\n /**\n * A function to manipulate the data returned by a failed query or mutation.\n */\n transformErrorResponse?(baseQueryReturnValue: BaseQueryError, meta: BaseQueryMeta, arg: QueryArg): unknown;\n /**\n * Defaults to `true`.\n *\n * Most apps should leave this setting on. The only time it can be a performance issue\n * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\n * you're unable to paginate it.\n *\n * For details of how this works, please see the below. When it is set to `false`,\n * every request will cause subscribed components to rerender, even when the data has not changed.\n *\n * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\n */\n structuralSharing?: boolean;\n};\ntype EndpointDefinitionWithQueryFn = {\n /**\n * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.\n *\n * @example\n * ```ts\n * // codeblock-meta title=\"Basic queryFn example\"\n *\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n * interface Post {\n * id: number\n * name: string\n * }\n * type PostsResponse = Post[]\n *\n * const api = createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * endpoints: (build) => ({\n * getPosts: build.query({\n * query: () => 'posts',\n * }),\n * flipCoin: build.query<'heads' | 'tails', void>({\n * // highlight-start\n * queryFn(arg, queryApi, extraOptions, baseQuery) {\n * const randomVal = Math.random()\n * if (randomVal < 0.45) {\n * return { data: 'heads' }\n * }\n * if (randomVal < 0.9) {\n * return { data: 'tails' }\n * }\n * return { error: { status: 500, statusText: 'Internal Server Error', data: \"Coin landed on its edge!\" } }\n * }\n * // highlight-end\n * })\n * })\n * })\n * ```\n */\n queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions, baseQuery: (arg: Parameters[0]) => ReturnType): MaybePromise, BaseQueryMeta>>;\n query?: never;\n transformResponse?: never;\n transformErrorResponse?: never;\n /**\n * Defaults to `true`.\n *\n * Most apps should leave this setting on. The only time it can be a performance issue\n * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\n * you're unable to paginate it.\n *\n * For details of how this works, please see the below. When it is set to `false`,\n * every request will cause subscribed components to rerender, even when the data has not changed.\n *\n * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\n */\n structuralSharing?: boolean;\n};\ntype BaseEndpointTypes = {\n QueryArg: QueryArg;\n BaseQuery: BaseQuery;\n ResultType: ResultType;\n};\nexport type BaseEndpointDefinition = (([CastAny, {}>] extends [NEVER] ? never : EndpointDefinitionWithQuery) | EndpointDefinitionWithQueryFn) & {\n /* phantom type */\n [resultType]?: ResultType;\n /* phantom type */\n [baseQuery]?: BaseQuery;\n} & HasRequiredProps, {\n extraOptions: BaseQueryExtraOptions;\n}, {\n extraOptions?: BaseQueryExtraOptions;\n}>;\nexport enum DefinitionType {\n query = 'query',\n mutation = 'mutation',\n}\nexport type GetResultDescriptionFn = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => ReadonlyArray