UNPKG

@reduxjs/toolkit

Version:

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

643 lines (642 loc) • 24.4 kB
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); //#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 let _reduxjs_toolkit = require("@reduxjs/toolkit"); let react_redux = require("react-redux"); let reselect = require("reselect"); let react = require("react"); react = __toESM(react); let _reduxjs_toolkit_query = require("@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 = (0, react.useRef)(queryArgs); const copy = (0, react.useMemo)(() => (0, _reduxjs_toolkit_query.copyWithStructuralSharing)(cache.current, queryArgs), [queryArgs]); (0, react.useEffect)(() => { if (cache.current !== copy) cache.current = copy; }, [copy]); return copy; } //#endregion //#region src/query/react/useShallowStableValue.ts function useShallowStableValue(value) { const cache = (0, react.useRef)(value); (0, react.useEffect)(() => { if (!(0, react_redux.shallowEqual)(cache.current, value)) cache.current = value; }, [value]); return (0, react_redux.shallowEqual)(cache.current, value) ? cache.current : value; } //#endregion //#region src/query/react/buildHooks.ts 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 ? react.useLayoutEffect : react.useEffect; const useIsomorphicLayoutEffect = /* @__PURE__ */ getUseIsomorphicLayoutEffect(); const noPendingQueryStateSelector = (selected) => { if (selected.isUninitialized) return { ...selected, isUninitialized: false, isFetching: true, isLoading: selected.data !== void 0 ? false : true, status: _reduxjs_toolkit_query.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() : react.useEffect; const unsubscribePromiseRef = (ref) => { ref.current?.unsubscribe?.(); ref.current = void 0; }; const endpointDefinitions = context.endpointDefinitions; return { buildQueryHooks, buildInfiniteQueryHooks, buildMutationHook, usePrefetch }; function queryStatePreSelector(currentState, lastResult, queryArgs) { if (lastResult?.endpointName && currentState.isUninitialized) { const { endpointName } = lastResult; const endpointDefinition = endpointDefinitions[endpointName]; if (queryArgs !== _reduxjs_toolkit_query.skipToken && serializeQueryArgs({ queryArgs: lastResult.originalArgs, endpointDefinition, endpointName }) === serializeQueryArgs({ queryArgs, endpointDefinition, endpointName })) lastResult = void 0; } let data = currentState.data; if (data === void 0) data = 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 { ...currentState, data, currentData: currentState.data, isFetching, isLoading, isSuccess }; } function infiniteQueryStatePreSelector(currentState, lastResult, queryArgs) { if (lastResult?.endpointName && currentState.isUninitialized) { const { endpointName } = lastResult; const endpointDefinition = endpointDefinitions[endpointName]; if (queryArgs !== _reduxjs_toolkit_query.skipToken && serializeQueryArgs({ queryArgs: lastResult.originalArgs, endpointDefinition, endpointName }) === serializeQueryArgs({ queryArgs, endpointDefinition, endpointName })) lastResult = void 0; } let data = currentState.data; if (data === void 0) data = 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 { ...currentState, data, currentData: currentState.data, isFetching, isLoading, isSuccess }; } function usePrefetch(endpointName, defaultOptions) { const dispatch = useDispatch(); const stableDefaultOptions = useShallowStableValue(defaultOptions); return (0, react.useCallback)((arg, options) => dispatch(api.util.prefetch(endpointName, arg, { ...stableDefaultOptions, ...options })), [ endpointName, dispatch, stableDefaultOptions ]); } function useQuerySubscriptionCommonImpl(endpointName, arg, { refetchOnReconnect, refetchOnFocus, refetchOnMountOrArgChange, skip = false, pollingInterval = 0, skipPollingIfUnfocused = false, ...rest } = {}) { const { initiate } = api.endpoints[endpointName]; const dispatch = useDispatch(); const subscriptionSelectorsRef = (0, react.useRef)(void 0); if (!subscriptionSelectorsRef.current) { const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions()); if (typeof returnedValue !== "object" || typeof returnedValue?.type === "string") throw new Error(`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 ? _reduxjs_toolkit_query.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 = (0, react.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(() => { const lastPromise = promiseRef.current; if (stableArg === _reduxjs_toolkit_query.skipToken) { lastPromise?.unsubscribe(); promiseRef.current = void 0; return; } const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions; if (!lastPromise || lastPromise.arg !== stableArg) { lastPromise?.unsubscribe(); const promise = dispatch(initiate(stableArg, { 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 ? _reduxjs_toolkit_query.skipToken : arg); const lastValue = (0, react.useRef)(void 0); const latestDefaultResult = (0, react.useRef)(void 0); const selectDefaultResult = (0, react.useMemo)(() => createSelector([ select(stableArg), (_, lastResult) => lastResult, (_) => stableArg ], preSelector, { memoizeOptions: { resultEqualityCheck: react_redux.shallowEqual } }), [select, stableArg]); const currentState = useSelector((0, react.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]), react_redux.shallowEqual); useIsomorphicLayoutEffect(() => { lastValue.current = latestDefaultResult.current; }); return currentState; }; return useQueryState; } function usePromiseRefUnsubscribeOnUnmount(promiseRef) { (0, react.useEffect)(() => { return () => { unsubscribePromiseRef(promiseRef); }; }, [promiseRef]); } function refetchOrErrorIfUnmounted(promiseRef) { if (!promiseRef.current) throw new Error("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 (0, react.useMemo)(() => ({ refetch: () => refetchOrErrorIfUnmounted(promiseRef) }), [promiseRef]); }; const useLazyQuerySubscription = ({ refetchOnReconnect, refetchOnFocus, pollingInterval = 0, skipPollingIfUnfocused = false } = {}) => { const { initiate } = api.endpoints[endpointName]; const dispatch = useDispatch(); const [arg, setArg] = (0, react.useState)(UNINITIALIZED_VALUE); const promiseRef = (0, react.useRef)(void 0); const stableSubscriptionOptions = useShallowStableValue({ refetchOnReconnect, refetchOnFocus, pollingInterval, skipPollingIfUnfocused }); usePossiblyImmediateEffect(() => { const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions; if (stableSubscriptionOptions !== lastSubscriptionOptions) promiseRef.current?.updateSubscriptionOptions(stableSubscriptionOptions); }, [stableSubscriptionOptions]); const subscriptionOptionsRef = (0, react.useRef)(stableSubscriptionOptions); usePossiblyImmediateEffect(() => { subscriptionOptionsRef.current = stableSubscriptionOptions; }, [stableSubscriptionOptions]); const trigger = (0, react.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 = (0, react.useCallback)(() => { if (promiseRef.current?.queryCacheKey) dispatch(api.internalActions.removeQueryResult({ queryCacheKey: promiseRef.current?.queryCacheKey })); }, [dispatch]); (0, react.useEffect)(() => { return () => { unsubscribePromiseRef(promiseRef); }; }, []); (0, react.useEffect)(() => { if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) trigger(arg, true); }, [arg, trigger]); return (0, react.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, { ...options, skip: arg === UNINITIALIZED_VALUE }); const info = (0, react.useMemo)(() => ({ lastArg: arg }), [arg]); return (0, react.useMemo)(() => [ trigger, { ...queryStateResults, reset }, info ], [ trigger, queryStateResults, reset, info ]); }, useQuery(arg, options) { const querySubscriptionResults = useQuerySubscription(arg, options); const queryStateResults = useQueryState(arg, { selectFromResult: arg === _reduxjs_toolkit_query.skipToken || options?.skip ? void 0 : noPendingQueryStateSelector, ...options }); const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS); (0, react.useDebugValue)(debugValue); return (0, react.useMemo)(() => ({ ...queryStateResults, ...querySubscriptionResults }), [queryStateResults, querySubscriptionResults]); } }; } function buildInfiniteQueryHooks(endpointName) { const useInfiniteQuerySubscription = (arg, options = {}) => { const [promiseRef, dispatch, initiate, stableSubscriptionOptions] = useQuerySubscriptionCommonImpl(endpointName, arg, options); const subscriptionOptionsRef = (0, react.useRef)(stableSubscriptionOptions); usePossiblyImmediateEffect(() => { subscriptionOptionsRef.current = stableSubscriptionOptions; }, [stableSubscriptionOptions]); const hookRefetchCachedPages = options.refetchCachedPages; const stableHookRefetchCachedPages = useShallowStableValue(hookRefetchCachedPages); const trigger = (0, react.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 ? _reduxjs_toolkit_query.skipToken : arg); const refetch = (0, react.useCallback)((options) => { if (!promiseRef.current) throw new Error("Cannot refetch a query that has not been started yet."); const mergedOptions = { refetchCachedPages: options?.refetchCachedPages ?? stableHookRefetchCachedPages }; return promiseRef.current.refetch(mergedOptions); }, [promiseRef, stableHookRefetchCachedPages]); return (0, react.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, { selectFromResult: arg === _reduxjs_toolkit_query.skipToken || options?.skip ? void 0 : noPendingQueryStateSelector, ...options }); const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS, "hasNextPage", "hasPreviousPage"); (0, react.useDebugValue)(debugValue); return (0, react.useMemo)(() => ({ ...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] = (0, react.useState)(); (0, react.useEffect)(() => () => { if (!promise?.arg.fixedCacheKey) promise?.reset(); }, [promise]); const triggerMutation = (0, react.useCallback)(function(arg) { const promise = dispatch(initiate(arg, { fixedCacheKey })); setPromise(promise); return promise; }, [ dispatch, initiate, fixedCacheKey ]); const { requestId } = promise || {}; const selectDefaultResult = (0, react.useMemo)(() => select({ fixedCacheKey, requestId: promise?.requestId }), [ fixedCacheKey, promise, select ]); const currentState = useSelector((0, react.useMemo)(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]), react_redux.shallowEqual); const originalArgs = fixedCacheKey == null ? promise?.arg.originalArgs : void 0; const reset = (0, react.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"); (0, react.useDebugValue)(debugValue); const finalState = (0, react.useMemo)(() => ({ ...currentState, originalArgs, reset }), [ currentState, originalArgs, reset ]); return (0, react.useMemo)(() => [triggerMutation, finalState], [triggerMutation, finalState]); }; } } //#endregion //#region src/query/react/module.ts const reactHooksModuleName = /* @__PURE__ */ Symbol(); const reactHooksModule = ({ batch = react_redux.batch, hooks = { useDispatch: react_redux.useDispatch, useSelector: react_redux.useSelector, useStore: react_redux.useStore }, createSelector = reselect.createSelector, unstable__sideEffectsInRender = false, ...rest } = {}) => { { 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(`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, hooks, unstable__sideEffectsInRender, createSelector }, serializeQueryArgs, context }); safeAssign(anyApi, { usePrefetch }); safeAssign(context, { batch }); 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 || react_redux.ReactReduxContext; if ((0, react.useContext)(context)) throw new Error("Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup."); const [store] = react.useState(() => (0, _reduxjs_toolkit.configureStore)({ reducer: { [props.api.reducerPath]: props.api.reducer }, middleware: (gDM) => gDM().concat(props.api.middleware) })); (0, react.useEffect)(() => props.setupListeners === false ? void 0 : (0, _reduxjs_toolkit_query.setupListeners)(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]); return /* @__PURE__ */ react.createElement(react_redux.Provider, { store, context }, props.children); } //#endregion //#region src/query/react/index.ts const createApi = /* @__PURE__ */ (0, _reduxjs_toolkit_query.buildCreateApi)((0, _reduxjs_toolkit_query.coreModule)(), reactHooksModule()); //#endregion exports.ApiProvider = ApiProvider; exports.UNINITIALIZED_VALUE = UNINITIALIZED_VALUE; exports.createApi = createApi; exports.reactHooksModule = reactHooksModule; exports.reactHooksModuleName = reactHooksModuleName; Object.keys(_reduxjs_toolkit_query).forEach(function(k) { if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { enumerable: true, get: function() { return _reduxjs_toolkit_query[k]; } }); }); //# sourceMappingURL=rtk-query-react.development.cjs.map