UNPKG

@reduxjs/toolkit

Version:

The official, opinionated, batteries-included toolset for efficient Redux development

698 lines (697 loc) • 28 kB
import { QueryStatus, buildCreateApi, copyWithStructuralSharing, coreModule, setupListeners, skipToken } from "@reduxjs/toolkit/query"; import { configureStore, formatProdErrorMessage } from "@reduxjs/toolkit"; import { Provider, ReactReduxContext, batch, shallowEqual, useDispatch, useSelector, useStore } from "react-redux"; import { createSelector } from "reselect"; import * as React from "react"; import { useCallback, useContext, useDebugValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; export * from "@reduxjs/toolkit/query"; //#region src/query/utils/capitalize.ts function capitalize(str) { return str.replace(str[0], str[0].toUpperCase()); } //#endregion //#region src/query/utils/countObjectKeys.ts function countObjectKeys(obj) { let count = 0; for (const _key in obj) count++; return count; } //#endregion //#region src/query/endpointDefinitions.ts const ENDPOINT_QUERY = "query"; const ENDPOINT_MUTATION = "mutation"; const ENDPOINT_INFINITEQUERY = "infinitequery"; function isQueryDefinition(e) { return e.type === ENDPOINT_QUERY; } function isMutationDefinition(e) { return e.type === ENDPOINT_MUTATION; } function isInfiniteQueryDefinition(e) { return e.type === ENDPOINT_INFINITEQUERY; } //#endregion //#region src/query/tsHelpers.ts function safeAssign(target, ...args) { return Object.assign(target, ...args); } //#endregion //#region src/query/react/constants.ts const UNINITIALIZED_VALUE = Symbol(); //#endregion //#region src/query/react/useSerializedStableValue.ts function useStableQueryArgs(queryArgs) { const cache = useRef(queryArgs); const copy = useMemo(() => copyWithStructuralSharing(cache.current, queryArgs), [queryArgs]); useEffect(() => { if (cache.current !== copy) cache.current = copy; }, [copy]); return copy; } //#endregion //#region src/query/react/useShallowStableValue.ts function useShallowStableValue(value) { const cache = useRef(value); useEffect(() => { if (!shallowEqual(cache.current, value)) cache.current = value; }, [value]); return shallowEqual(cache.current, value) ? cache.current : value; } //#endregion //#region \0@oxc-project+runtime@0.144.0/helpers/esm/typeof.js function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) { return typeof o; } : function(o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } //#endregion //#region \0@oxc-project+runtime@0.144.0/helpers/esm/toPrimitive.js function toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } //#endregion //#region \0@oxc-project+runtime@0.144.0/helpers/esm/toPropertyKey.js function toPropertyKey(t) { var i = toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } //#endregion //#region \0@oxc-project+runtime@0.144.0/helpers/esm/defineProperty.js function _defineProperty(e, r, t) { return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } //#endregion //#region \0@oxc-project+runtime@0.144.0/helpers/esm/objectSpread2.js function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function(r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function(r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } //#endregion //#region \0@oxc-project+runtime@0.144.0/helpers/esm/objectWithoutPropertiesLoose.js function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; } //#endregion //#region \0@oxc-project+runtime@0.144.0/helpers/esm/objectWithoutProperties.js function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } //#endregion //#region src/query/react/buildHooks.ts const _excluded$1 = [ "refetchOnReconnect", "refetchOnFocus", "refetchOnMountOrArgChange", "skip", "pollingInterval", "skipPollingIfUnfocused" ]; const canUseDOM = () => !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"); const isDOM = /* @__PURE__ */ canUseDOM(); const isRunningInReactNative = () => typeof navigator !== "undefined" && navigator.product === "ReactNative"; const isReactNative = /* @__PURE__ */ isRunningInReactNative(); const getUseIsomorphicLayoutEffect = () => isDOM || isReactNative ? useLayoutEffect : useEffect; const useIsomorphicLayoutEffect = /* @__PURE__ */ getUseIsomorphicLayoutEffect(); const noPendingQueryStateSelector = (selected) => { if (selected.isUninitialized) return _objectSpread2(_objectSpread2({}, selected), {}, { isUninitialized: false, isFetching: true, isLoading: selected.data !== void 0 ? false : true, status: QueryStatus.pending }); return selected; }; function pick(obj, ...keys) { const ret = {}; keys.forEach((key) => { ret[key] = obj[key]; }); return ret; } const COMMON_HOOK_DEBUG_FIELDS = [ "data", "status", "isLoading", "isSuccess", "isError", "error" ]; function buildHooks({ api, moduleOptions: { batch, hooks: { useDispatch, useSelector }, unstable__sideEffectsInRender, createSelector }, serializeQueryArgs, context }) { const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : useEffect; const unsubscribePromiseRef = (ref) => { var _ref$current, _ref$current$unsubscr; (_ref$current = ref.current) === null || _ref$current === void 0 || (_ref$current$unsubscr = _ref$current.unsubscribe) === null || _ref$current$unsubscr === void 0 || _ref$current$unsubscr.call(_ref$current); ref.current = void 0; }; const endpointDefinitions = context.endpointDefinitions; return { buildQueryHooks, buildInfiniteQueryHooks, buildMutationHook, usePrefetch }; function queryStatePreSelector(currentState, lastResult, queryArgs) { if ((lastResult === null || lastResult === void 0 ? void 0 : lastResult.endpointName) && currentState.isUninitialized) { const { endpointName } = lastResult; const endpointDefinition = endpointDefinitions[endpointName]; if (queryArgs !== skipToken && serializeQueryArgs({ queryArgs: lastResult.originalArgs, endpointDefinition, endpointName }) === serializeQueryArgs({ queryArgs, endpointDefinition, endpointName })) lastResult = void 0; } let data = currentState.data; if (data === void 0) data = lastResult === null || lastResult === void 0 ? void 0 : lastResult.data; const hasData = data !== void 0; const isFetching = currentState.isLoading; const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching; const isSuccess = currentState.isSuccess || hasData && (isFetching && currentState.error === void 0 || currentState.isUninitialized); return _objectSpread2(_objectSpread2({}, currentState), {}, { data, currentData: currentState.data, isFetching, isLoading, isSuccess }); } function infiniteQueryStatePreSelector(currentState, lastResult, queryArgs) { if ((lastResult === null || lastResult === void 0 ? void 0 : lastResult.endpointName) && currentState.isUninitialized) { const { endpointName } = lastResult; const endpointDefinition = endpointDefinitions[endpointName]; if (queryArgs !== skipToken && serializeQueryArgs({ queryArgs: lastResult.originalArgs, endpointDefinition, endpointName }) === serializeQueryArgs({ queryArgs, endpointDefinition, endpointName })) lastResult = void 0; } let data = currentState.data; if (data === void 0) data = lastResult === null || lastResult === void 0 ? void 0 : lastResult.data; const hasData = data !== void 0; const isFetching = currentState.isLoading; const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching; const isSuccess = currentState.isSuccess || hasData && (isFetching && currentState.error === void 0 || currentState.isUninitialized); return _objectSpread2(_objectSpread2({}, currentState), {}, { data, currentData: currentState.data, isFetching, isLoading, isSuccess }); } function usePrefetch(endpointName, defaultOptions) { const dispatch = useDispatch(); const stableDefaultOptions = useShallowStableValue(defaultOptions); return useCallback((arg, options) => dispatch(api.util.prefetch(endpointName, arg, _objectSpread2(_objectSpread2({}, stableDefaultOptions), options))), [ endpointName, dispatch, stableDefaultOptions ]); } function useQuerySubscriptionCommonImpl(endpointName, arg, _ref = {}) { let { refetchOnReconnect, refetchOnFocus, refetchOnMountOrArgChange, skip = false, pollingInterval = 0, skipPollingIfUnfocused = false } = _ref, rest = _objectWithoutProperties(_ref, _excluded$1); const { initiate } = api.endpoints[endpointName]; const dispatch = useDispatch(); const subscriptionSelectorsRef = useRef(void 0); if (!subscriptionSelectorsRef.current) { const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions()); if (process.env.NODE_ENV !== "production") { if (typeof returnedValue !== "object" || typeof (returnedValue === null || returnedValue === void 0 ? void 0 : returnedValue.type) === "string") 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. You must add the middleware for RTK-Query to function correctly!`); } subscriptionSelectorsRef.current = returnedValue; } const stableArg = useStableQueryArgs(skip ? skipToken : arg); const stableSubscriptionOptions = useShallowStableValue({ refetchOnReconnect, refetchOnFocus, pollingInterval, skipPollingIfUnfocused }); const initialPageParam = rest.initialPageParam; const stableInitialPageParam = useShallowStableValue(initialPageParam); const refetchCachedPages = rest.refetchCachedPages; const stableRefetchCachedPages = useShallowStableValue(refetchCachedPages); const promiseRef = useRef(void 0); let { queryCacheKey, requestId } = promiseRef.current || {}; let currentRenderHasSubscription = false; if (queryCacheKey && requestId) currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(queryCacheKey, requestId); const subscriptionRemoved = !currentRenderHasSubscription && promiseRef.current !== void 0; usePossiblyImmediateEffect(() => { if (subscriptionRemoved) promiseRef.current = void 0; }, [subscriptionRemoved]); usePossiblyImmediateEffect(() => { var _promiseRef$current; const lastPromise = promiseRef.current; if (typeof process !== "undefined" && process.env.NODE_ENV === "removeMeOnCompilation") console.log(subscriptionRemoved); if (stableArg === skipToken) { lastPromise === null || lastPromise === void 0 || lastPromise.unsubscribe(); promiseRef.current = void 0; return; } const lastSubscriptionOptions = (_promiseRef$current = promiseRef.current) === null || _promiseRef$current === void 0 ? void 0 : _promiseRef$current.subscriptionOptions; if (!lastPromise || lastPromise.arg !== stableArg) { lastPromise === null || lastPromise === void 0 || lastPromise.unsubscribe(); const promise = dispatch(initiate(stableArg, _objectSpread2({ subscriptionOptions: stableSubscriptionOptions, forceRefetch: refetchOnMountOrArgChange }, isInfiniteQueryDefinition(endpointDefinitions[endpointName]) ? { initialPageParam: stableInitialPageParam, refetchCachedPages: stableRefetchCachedPages } : {}))); promiseRef.current = promise; } else if (stableSubscriptionOptions !== lastSubscriptionOptions) lastPromise.updateSubscriptionOptions(stableSubscriptionOptions); }, [ dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved, stableInitialPageParam, stableRefetchCachedPages, endpointName ]); return [ promiseRef, dispatch, initiate, stableSubscriptionOptions ]; } function buildUseQueryState(endpointName, preSelector) { const useQueryState = (arg, { skip = false, selectFromResult } = {}) => { const { select } = api.endpoints[endpointName]; const stableArg = useStableQueryArgs(skip ? skipToken : arg); const lastValue = useRef(void 0); const latestDefaultResult = useRef(void 0); const selectDefaultResult = useMemo(() => createSelector([ select(stableArg), (_, lastResult) => lastResult, (_) => stableArg ], preSelector, { memoizeOptions: { resultEqualityCheck: shallowEqual } }), [select, stableArg]); const currentState = useSelector(useMemo(() => { const selectResult = selectFromResult ? createSelector([selectDefaultResult], selectFromResult, { devModeChecks: { identityFunctionCheck: "never" } }) : selectDefaultResult; return (state) => { const lastResult = lastValue.current; const result = selectResult(state, lastResult); latestDefaultResult.current = selectDefaultResult(state, lastResult); return result; }; }, [selectDefaultResult, selectFromResult]), shallowEqual); useIsomorphicLayoutEffect(() => { lastValue.current = latestDefaultResult.current; }); return currentState; }; return useQueryState; } function usePromiseRefUnsubscribeOnUnmount(promiseRef) { useEffect(() => { return () => { unsubscribePromiseRef(promiseRef); }; }, [promiseRef]); } function refetchOrErrorIfUnmounted(promiseRef) { if (!promiseRef.current) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(38) : "Cannot refetch a query that has not been started yet."); return promiseRef.current.refetch(); } function buildQueryHooks(endpointName) { const useQuerySubscription = (arg, options = {}) => { const [promiseRef] = useQuerySubscriptionCommonImpl(endpointName, arg, options); usePromiseRefUnsubscribeOnUnmount(promiseRef); return useMemo(() => ({ refetch: () => refetchOrErrorIfUnmounted(promiseRef) }), [promiseRef]); }; const useLazyQuerySubscription = ({ refetchOnReconnect, refetchOnFocus, pollingInterval = 0, skipPollingIfUnfocused = false } = {}) => { const { initiate } = api.endpoints[endpointName]; const dispatch = useDispatch(); const [arg, setArg] = useState(UNINITIALIZED_VALUE); const promiseRef = useRef(void 0); const stableSubscriptionOptions = useShallowStableValue({ refetchOnReconnect, refetchOnFocus, pollingInterval, skipPollingIfUnfocused }); usePossiblyImmediateEffect(() => { var _promiseRef$current2; const lastSubscriptionOptions = (_promiseRef$current2 = promiseRef.current) === null || _promiseRef$current2 === void 0 ? void 0 : _promiseRef$current2.subscriptionOptions; if (stableSubscriptionOptions !== lastSubscriptionOptions) { var _promiseRef$current3; (_promiseRef$current3 = promiseRef.current) === null || _promiseRef$current3 === void 0 || _promiseRef$current3.updateSubscriptionOptions(stableSubscriptionOptions); } }, [stableSubscriptionOptions]); const subscriptionOptionsRef = useRef(stableSubscriptionOptions); usePossiblyImmediateEffect(() => { subscriptionOptionsRef.current = stableSubscriptionOptions; }, [stableSubscriptionOptions]); const trigger = useCallback(function(arg, preferCacheValue = false) { let promise; batch(() => { unsubscribePromiseRef(promiseRef); promiseRef.current = promise = dispatch(initiate(arg, { subscriptionOptions: subscriptionOptionsRef.current, forceRefetch: !preferCacheValue })); setArg(arg); }); return promise; }, [dispatch, initiate]); const reset = useCallback(() => { var _promiseRef$current4; if ((_promiseRef$current4 = promiseRef.current) === null || _promiseRef$current4 === void 0 ? void 0 : _promiseRef$current4.queryCacheKey) { var _promiseRef$current5; dispatch(api.internalActions.removeQueryResult({ queryCacheKey: (_promiseRef$current5 = promiseRef.current) === null || _promiseRef$current5 === void 0 ? void 0 : _promiseRef$current5.queryCacheKey })); } }, [dispatch]); useEffect(() => { return () => { unsubscribePromiseRef(promiseRef); }; }, []); useEffect(() => { if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) trigger(arg, true); }, [arg, trigger]); return useMemo(() => [ trigger, arg, { reset } ], [ trigger, arg, reset ]); }; const useQueryState = buildUseQueryState(endpointName, queryStatePreSelector); return { useQueryState, useQuerySubscription, useLazyQuerySubscription, useLazyQuery(options) { const [trigger, arg, { reset }] = useLazyQuerySubscription(options); const queryStateResults = useQueryState(arg, _objectSpread2(_objectSpread2({}, options), {}, { skip: arg === UNINITIALIZED_VALUE })); const info = useMemo(() => ({ lastArg: arg }), [arg]); return useMemo(() => [ trigger, _objectSpread2(_objectSpread2({}, queryStateResults), {}, { reset }), info ], [ trigger, queryStateResults, reset, info ]); }, useQuery(arg, options) { const querySubscriptionResults = useQuerySubscription(arg, options); const queryStateResults = useQueryState(arg, _objectSpread2({ selectFromResult: arg === skipToken || (options === null || options === void 0 ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector }, options)); const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS); useDebugValue(debugValue); return useMemo(() => _objectSpread2(_objectSpread2({}, queryStateResults), querySubscriptionResults), [queryStateResults, querySubscriptionResults]); } }; } function buildInfiniteQueryHooks(endpointName) { const useInfiniteQuerySubscription = (arg, options = {}) => { const [promiseRef, dispatch, initiate, stableSubscriptionOptions] = useQuerySubscriptionCommonImpl(endpointName, arg, options); const subscriptionOptionsRef = useRef(stableSubscriptionOptions); usePossiblyImmediateEffect(() => { subscriptionOptionsRef.current = stableSubscriptionOptions; }, [stableSubscriptionOptions]); const hookRefetchCachedPages = options.refetchCachedPages; const stableHookRefetchCachedPages = useShallowStableValue(hookRefetchCachedPages); const trigger = useCallback(function(arg, direction) { let promise; batch(() => { unsubscribePromiseRef(promiseRef); promiseRef.current = promise = dispatch(initiate(arg, { subscriptionOptions: subscriptionOptionsRef.current, direction })); }); return promise; }, [ promiseRef, dispatch, initiate ]); usePromiseRefUnsubscribeOnUnmount(promiseRef); const stableArg = useStableQueryArgs(options.skip ? skipToken : arg); const refetch = useCallback((options) => { var _options$refetchCache; if (!promiseRef.current) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(38) : "Cannot refetch a query that has not been started yet."); const mergedOptions = { refetchCachedPages: (_options$refetchCache = options === null || options === void 0 ? void 0 : options.refetchCachedPages) !== null && _options$refetchCache !== void 0 ? _options$refetchCache : stableHookRefetchCachedPages }; return promiseRef.current.refetch(mergedOptions); }, [promiseRef, stableHookRefetchCachedPages]); return useMemo(() => { const fetchNextPage = () => { return trigger(stableArg, "forward"); }; const fetchPreviousPage = () => { return trigger(stableArg, "backward"); }; return { trigger, refetch, fetchNextPage, fetchPreviousPage }; }, [ refetch, trigger, stableArg ]); }; const useInfiniteQueryState = buildUseQueryState(endpointName, infiniteQueryStatePreSelector); return { useInfiniteQueryState, useInfiniteQuerySubscription, useInfiniteQuery(arg, options) { const { refetch, fetchNextPage, fetchPreviousPage } = useInfiniteQuerySubscription(arg, options); const queryStateResults = useInfiniteQueryState(arg, _objectSpread2({ selectFromResult: arg === skipToken || (options === null || options === void 0 ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector }, options)); const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS, "hasNextPage", "hasPreviousPage"); useDebugValue(debugValue); return useMemo(() => _objectSpread2(_objectSpread2({}, queryStateResults), {}, { fetchNextPage, fetchPreviousPage, refetch }), [ queryStateResults, fetchNextPage, fetchPreviousPage, refetch ]); } }; } function buildMutationHook(name) { return ({ selectFromResult, fixedCacheKey } = {}) => { const { select, initiate } = api.endpoints[name]; const dispatch = useDispatch(); const [promise, setPromise] = useState(); useEffect(() => () => { if (!(promise === null || promise === void 0 ? void 0 : promise.arg.fixedCacheKey)) promise === null || promise === void 0 || promise.reset(); }, [promise]); const triggerMutation = useCallback(function(arg) { const promise = dispatch(initiate(arg, { fixedCacheKey })); setPromise(promise); return promise; }, [ dispatch, initiate, fixedCacheKey ]); const { requestId } = promise || {}; const selectDefaultResult = useMemo(() => select({ fixedCacheKey, requestId: promise === null || promise === void 0 ? void 0 : promise.requestId }), [ fixedCacheKey, promise, select ]); const currentState = useSelector(useMemo(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]), shallowEqual); const originalArgs = fixedCacheKey == null ? promise === null || promise === void 0 ? void 0 : promise.arg.originalArgs : void 0; const reset = useCallback(() => { batch(() => { if (promise) setPromise(void 0); if (fixedCacheKey) dispatch(api.internalActions.removeMutationResult({ requestId, fixedCacheKey })); }); }, [ dispatch, fixedCacheKey, promise, requestId ]); const debugValue = pick(currentState, ...COMMON_HOOK_DEBUG_FIELDS, "endpointName"); useDebugValue(debugValue); const finalState = useMemo(() => _objectSpread2(_objectSpread2({}, currentState), {}, { originalArgs, reset }), [ currentState, originalArgs, reset ]); return useMemo(() => [triggerMutation, finalState], [triggerMutation, finalState]); }; } } //#endregion //#region src/query/react/module.ts const _excluded = [ "batch", "hooks", "createSelector", "unstable__sideEffectsInRender" ]; const reactHooksModuleName = /* @__PURE__ */ Symbol(); const reactHooksModule = (_ref = {}) => { let { batch: batch$1 = batch, hooks = { useDispatch, useSelector, useStore }, createSelector: createSelector$1 = createSelector, unstable__sideEffectsInRender = false } = _ref, rest = _objectWithoutProperties(_ref, _excluded); if (process.env.NODE_ENV !== "production") { const hookNames = [ "useDispatch", "useSelector", "useStore" ]; let warned = false; for (const hookName of hookNames) { if (countObjectKeys(rest) > 0) { if (rest[hookName]) { if (!warned) { 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 } })`"); warned = true; } } hooks[hookName] = rest[hookName]; } if (typeof hooks[hookName] !== "function") 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.`); } } return { name: reactHooksModuleName, init(api, { serializeQueryArgs }, context) { const anyApi = api; const { buildQueryHooks, buildInfiniteQueryHooks, buildMutationHook, usePrefetch } = buildHooks({ api, moduleOptions: { batch: batch$1, hooks, unstable__sideEffectsInRender, createSelector: createSelector$1 }, serializeQueryArgs, context }); safeAssign(anyApi, { usePrefetch }); safeAssign(context, { batch: batch$1 }); return { injectEndpoint(endpointName, definition) { if (isQueryDefinition(definition)) { const { useQuery, useLazyQuery, useLazyQuerySubscription, useQueryState, useQuerySubscription } = buildQueryHooks(endpointName); safeAssign(anyApi.endpoints[endpointName], { useQuery, useLazyQuery, useLazyQuerySubscription, useQueryState, useQuerySubscription }); api[`use${capitalize(endpointName)}Query`] = useQuery; api[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery; } if (isMutationDefinition(definition)) { const useMutation = buildMutationHook(endpointName); safeAssign(anyApi.endpoints[endpointName], { useMutation }); api[`use${capitalize(endpointName)}Mutation`] = useMutation; } else if (isInfiniteQueryDefinition(definition)) { const { useInfiniteQuery, useInfiniteQuerySubscription, useInfiniteQueryState } = buildInfiniteQueryHooks(endpointName); safeAssign(anyApi.endpoints[endpointName], { useInfiniteQuery, useInfiniteQuerySubscription, useInfiniteQueryState }); api[`use${capitalize(endpointName)}InfiniteQuery`] = useInfiniteQuery; } } }; } }; }; //#endregion //#region src/query/react/ApiProvider.tsx function ApiProvider(props) { const context = props.context || ReactReduxContext; if (useContext(context)) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(35) : "Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup."); const [store] = React.useState(() => configureStore({ reducer: { [props.api.reducerPath]: props.api.reducer }, middleware: (gDM) => gDM().concat(props.api.middleware) })); useEffect(() => props.setupListeners === false ? void 0 : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]); return /* @__PURE__ */ React.createElement(Provider, { store, context }, props.children); } //#endregion //#region src/query/react/index.ts const createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule()); //#endregion export { ApiProvider, UNINITIALIZED_VALUE, createApi, reactHooksModule, reactHooksModuleName }; //# sourceMappingURL=rtk-query-react.legacy-esm.js.map