Version 1.0.2 mit node_modules Verzeichnis

This commit is contained in:
ISA
2024-10-02 07:58:24 +02:00
parent f353a06b1b
commit 62b6e55a0a
68228 changed files with 4548477 additions and 651 deletions

View File

@@ -0,0 +1,6 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./rtk-query-react.production.min.cjs')
} else {
module.exports = require('./rtk-query-react.development.cjs')
}

View File

@@ -0,0 +1,651 @@
"use strict";
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 __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/query/react/index.ts
var react_exports = {};
__export(react_exports, {
ApiProvider: () => ApiProvider,
UNINITIALIZED_VALUE: () => UNINITIALIZED_VALUE,
createApi: () => createApi,
reactHooksModule: () => reactHooksModule,
reactHooksModuleName: () => reactHooksModuleName
});
module.exports = __toCommonJS(react_exports);
var import_query3 = require("@reduxjs/toolkit/query");
// src/query/react/module.ts
var import_toolkit3 = require("@reduxjs/toolkit");
var import_react_redux3 = require("react-redux");
var import_reselect = require("reselect");
// src/query/endpointDefinitions.ts
function isQueryDefinition(e) {
return e.type === "query" /* query */;
}
function isMutationDefinition(e) {
return e.type === "mutation" /* mutation */;
}
// src/query/tsHelpers.ts
function safeAssign(target, ...args) {
return Object.assign(target, ...args);
}
// src/query/utils/capitalize.ts
function capitalize(str) {
return str.replace(str[0], str[0].toUpperCase());
}
// src/query/core/rtkImports.ts
var import_toolkit = require("@reduxjs/toolkit");
// src/query/utils/countObjectKeys.ts
function countObjectKeys(obj) {
let count = 0;
for (const _key in obj) {
count++;
}
return count;
}
// src/query/react/buildHooks.ts
var import_toolkit2 = require("@reduxjs/toolkit");
var import_query = require("@reduxjs/toolkit/query");
var import_react3 = require("react");
var import_react_redux2 = require("react-redux");
// src/query/defaultSerializeQueryArgs.ts
var cache = WeakMap ? /* @__PURE__ */ new WeakMap() : void 0;
var defaultSerializeQueryArgs = ({
endpointName,
queryArgs
}) => {
let serialized = "";
const cached = cache?.get(queryArgs);
if (typeof cached === "string") {
serialized = cached;
} else {
const stringified = JSON.stringify(queryArgs, (key, value) => {
value = typeof value === "bigint" ? {
$bigint: value.toString()
} : value;
value = (0, import_toolkit.isPlainObject)(value) ? Object.keys(value).sort().reduce((acc, key2) => {
acc[key2] = value[key2];
return acc;
}, {}) : value;
return value;
});
if ((0, import_toolkit.isPlainObject)(queryArgs)) {
cache?.set(queryArgs, stringified);
}
serialized = stringified;
}
return `${endpointName}(${serialized})`;
};
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/useSerializedStableValue.ts
var import_react = require("react");
function useStableQueryArgs(queryArgs, serialize, endpointDefinition, endpointName) {
const incoming = (0, import_react.useMemo)(() => ({
queryArgs,
serialized: typeof queryArgs == "object" ? serialize({
queryArgs,
endpointDefinition,
endpointName
}) : queryArgs
}), [queryArgs, serialize, endpointDefinition, endpointName]);
const cache2 = (0, import_react.useRef)(incoming);
(0, import_react.useEffect)(() => {
if (cache2.current.serialized !== incoming.serialized) {
cache2.current = incoming;
}
}, [incoming]);
return cache2.current.serialized === incoming.serialized ? cache2.current.queryArgs : queryArgs;
}
// src/query/react/useShallowStableValue.ts
var import_react2 = require("react");
var import_react_redux = require("react-redux");
function useShallowStableValue(value) {
const cache2 = (0, import_react2.useRef)(value);
(0, import_react2.useEffect)(() => {
if (!(0, import_react_redux.shallowEqual)(cache2.current, value)) {
cache2.current = value;
}
}, [value]);
return (0, import_react_redux.shallowEqual)(cache2.current, value) ? cache2.current : value;
}
// src/query/react/buildHooks.ts
var canUseDOM = () => !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
var isDOM = /* @__PURE__ */ canUseDOM();
var isRunningInReactNative = () => typeof navigator !== "undefined" && navigator.product === "ReactNative";
var isReactNative = /* @__PURE__ */ isRunningInReactNative();
var getUseIsomorphicLayoutEffect = () => isDOM || isReactNative ? import_react3.useLayoutEffect : import_react3.useEffect;
var useIsomorphicLayoutEffect = /* @__PURE__ */ getUseIsomorphicLayoutEffect();
var noPendingQueryStateSelector = (selected) => {
if (selected.isUninitialized) {
return {
...selected,
isUninitialized: false,
isFetching: true,
isLoading: selected.data !== void 0 ? false : true,
status: import_query.QueryStatus.pending
};
}
return selected;
};
function buildHooks({
api,
moduleOptions: {
batch,
hooks: {
useDispatch,
useSelector,
useStore
},
unstable__sideEffectsInRender,
createSelector: createSelector2
},
serializeQueryArgs,
context
}) {
const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : import_react3.useEffect;
return {
buildQueryHooks,
buildMutationHook,
usePrefetch
};
function queryStatePreSelector(currentState, lastResult, queryArgs) {
if (lastResult?.endpointName && currentState.isUninitialized) {
const {
endpointName
} = lastResult;
const endpointDefinition = context.endpointDefinitions[endpointName];
if (serializeQueryArgs({
queryArgs: lastResult.originalArgs,
endpointDefinition,
endpointName
}) === serializeQueryArgs({
queryArgs,
endpointDefinition,
endpointName
})) lastResult = void 0;
}
let data = currentState.isSuccess ? currentState.data : lastResult?.data;
if (data === void 0) data = currentState.data;
const hasData = data !== void 0;
const isFetching = currentState.isLoading;
const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;
const isSuccess = currentState.isSuccess || isFetching && hasData;
return {
...currentState,
data,
currentData: currentState.data,
isFetching,
isLoading,
isSuccess
};
}
function usePrefetch(endpointName, defaultOptions) {
const dispatch = useDispatch();
const stableDefaultOptions = useShallowStableValue(defaultOptions);
return (0, import_react3.useCallback)((arg, options) => dispatch(api.util.prefetch(endpointName, arg, {
...stableDefaultOptions,
...options
})), [endpointName, dispatch, stableDefaultOptions]);
}
function buildQueryHooks(name) {
const useQuerySubscription = (arg, {
refetchOnReconnect,
refetchOnFocus,
refetchOnMountOrArgChange,
skip = false,
pollingInterval = 0,
skipPollingIfUnfocused = false
} = {}) => {
const {
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const subscriptionSelectorsRef = (0, import_react3.useRef)(void 0);
if (!subscriptionSelectorsRef.current) {
const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());
if (true) {
if (typeof returnedValue !== "object" || typeof returnedValue?.type === "string") {
throw new Error(false ? _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 ? import_query.skipToken : arg,
// Even if the user provided a per-endpoint `serializeQueryArgs` with
// a consistent return value, _here_ we want to use the default behavior
// so we can tell if _anything_ actually changed. Otherwise, we can end up
// with a case where the query args did change but the serialization doesn't,
// and then we never try to initiate a refetch.
defaultSerializeQueryArgs,
context.endpointDefinitions[name],
name
);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval,
skipPollingIfUnfocused
});
const lastRenderHadSubscription = (0, import_react3.useRef)(false);
const promiseRef = (0, import_react3.useRef)(void 0);
let {
queryCacheKey,
requestId
} = promiseRef.current || {};
let currentRenderHasSubscription = false;
if (queryCacheKey && requestId) {
currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(queryCacheKey, requestId);
}
const subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;
usePossiblyImmediateEffect(() => {
lastRenderHadSubscription.current = currentRenderHasSubscription;
});
usePossiblyImmediateEffect(() => {
if (subscriptionRemoved) {
promiseRef.current = void 0;
}
}, [subscriptionRemoved]);
usePossiblyImmediateEffect(() => {
const lastPromise = promiseRef.current;
if (typeof process !== "undefined" && false) {
console.log(subscriptionRemoved);
}
if (stableArg === import_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
}));
promiseRef.current = promise;
} else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved]);
(0, import_react3.useEffect)(() => {
return () => {
promiseRef.current?.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return (0, import_react3.useMemo)(() => ({
/**
* A method to manually refetch data for the query
*/
refetch: () => {
if (!promiseRef.current) throw new Error(false ? _formatProdErrorMessage2(38) : "Cannot refetch a query that has not been started yet.");
return promiseRef.current?.refetch();
}
}), []);
};
const useLazyQuerySubscription = ({
refetchOnReconnect,
refetchOnFocus,
pollingInterval = 0,
skipPollingIfUnfocused = false
} = {}) => {
const {
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const [arg, setArg] = (0, import_react3.useState)(UNINITIALIZED_VALUE);
const promiseRef = (0, import_react3.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, import_react3.useRef)(stableSubscriptionOptions);
usePossiblyImmediateEffect(() => {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
const trigger = (0, import_react3.useCallback)(function(arg2, preferCacheValue = false) {
let promise;
batch(() => {
promiseRef.current?.unsubscribe();
promiseRef.current = promise = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
return promise;
}, [dispatch, initiate]);
(0, import_react3.useEffect)(() => {
return () => {
promiseRef?.current?.unsubscribe();
};
}, []);
(0, import_react3.useEffect)(() => {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return (0, import_react3.useMemo)(() => [trigger, arg], [trigger, arg]);
};
const useQueryState = (arg, {
skip = false,
selectFromResult
} = {}) => {
const {
select
} = api.endpoints[name];
const stableArg = useStableQueryArgs(skip ? import_query.skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);
const lastValue = (0, import_react3.useRef)(void 0);
const selectDefaultResult = (0, import_react3.useMemo)(() => createSelector2([select(stableArg), (_, lastResult) => lastResult, (_) => stableArg], queryStatePreSelector, {
memoizeOptions: {
resultEqualityCheck: import_react_redux2.shallowEqual
}
}), [select, stableArg]);
const querySelector = (0, import_react3.useMemo)(() => selectFromResult ? createSelector2([selectDefaultResult], selectFromResult, {
devModeChecks: {
identityFunctionCheck: "never"
}
}) : selectDefaultResult, [selectDefaultResult, selectFromResult]);
const currentState = useSelector((state) => querySelector(state, lastValue.current), import_react_redux2.shallowEqual);
const store = useStore();
const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
useIsomorphicLayoutEffect(() => {
lastValue.current = newLastValue;
}, [newLastValue]);
return currentState;
};
return {
useQueryState,
useQuerySubscription,
useLazyQuerySubscription,
useLazyQuery(options) {
const [trigger, arg] = useLazyQuerySubscription(options);
const queryStateResults = useQueryState(arg, {
...options,
skip: arg === UNINITIALIZED_VALUE
});
const info = (0, import_react3.useMemo)(() => ({
lastArg: arg
}), [arg]);
return (0, import_react3.useMemo)(() => [trigger, queryStateResults, info], [trigger, queryStateResults, info]);
},
useQuery(arg, options) {
const querySubscriptionResults = useQuerySubscription(arg, options);
const queryStateResults = useQueryState(arg, {
selectFromResult: arg === import_query.skipToken || options?.skip ? void 0 : noPendingQueryStateSelector,
...options
});
const {
data,
status,
isLoading,
isSuccess,
isError,
error
} = queryStateResults;
(0, import_react3.useDebugValue)({
data,
status,
isLoading,
isSuccess,
isError,
error
});
return (0, import_react3.useMemo)(() => ({
...queryStateResults,
...querySubscriptionResults
}), [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return ({
selectFromResult,
fixedCacheKey
} = {}) => {
const {
select,
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const [promise, setPromise] = (0, import_react3.useState)();
(0, import_react3.useEffect)(() => () => {
if (!promise?.arg.fixedCacheKey) {
promise?.reset();
}
}, [promise]);
const triggerMutation = (0, import_react3.useCallback)(function(arg) {
const promise2 = dispatch(initiate(arg, {
fixedCacheKey
}));
setPromise(promise2);
return promise2;
}, [dispatch, initiate, fixedCacheKey]);
const {
requestId
} = promise || {};
const selectDefaultResult = (0, import_react3.useMemo)(() => select({
fixedCacheKey,
requestId: promise?.requestId
}), [fixedCacheKey, promise, select]);
const mutationSelector = (0, import_react3.useMemo)(() => selectFromResult ? createSelector2([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]);
const currentState = useSelector(mutationSelector, import_react_redux2.shallowEqual);
const originalArgs = fixedCacheKey == null ? promise?.arg.originalArgs : void 0;
const reset = (0, import_react3.useCallback)(() => {
batch(() => {
if (promise) {
setPromise(void 0);
}
if (fixedCacheKey) {
dispatch(api.internalActions.removeMutationResult({
requestId,
fixedCacheKey
}));
}
});
}, [dispatch, fixedCacheKey, promise, requestId]);
const {
endpointName,
data,
status,
isLoading,
isSuccess,
isError,
error
} = currentState;
(0, import_react3.useDebugValue)({
endpointName,
data,
status,
isLoading,
isSuccess,
isError,
error
});
const finalState = (0, import_react3.useMemo)(() => ({
...currentState,
originalArgs,
reset
}), [currentState, originalArgs, reset]);
return (0, import_react3.useMemo)(() => [triggerMutation, finalState], [triggerMutation, finalState]);
};
}
}
// src/query/react/module.ts
var reactHooksModuleName = /* @__PURE__ */ Symbol();
var reactHooksModule = ({
batch = import_react_redux3.batch,
hooks = {
useDispatch: import_react_redux3.useDispatch,
useSelector: import_react_redux3.useSelector,
useStore: import_react_redux3.useStore
},
createSelector: createSelector2 = import_reselect.createSelector,
unstable__sideEffectsInRender = false,
...rest
} = {}) => {
if (true) {
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(false ? _formatProdErrorMessage3(36) : `When using custom hooks for context, all ${hookNames.length} hooks need to be provided: ${hookNames.join(", ")}.
Hook ${hookName} was either not provided or not a function.`);
}
}
}
return {
name: reactHooksModuleName,
init(api, {
serializeQueryArgs
}, context) {
const anyApi = api;
const {
buildQueryHooks,
buildMutationHook,
usePrefetch
} = buildHooks({
api,
moduleOptions: {
batch,
hooks,
unstable__sideEffectsInRender,
createSelector: createSelector2
},
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;
} else if (isMutationDefinition(definition)) {
const useMutation = buildMutationHook(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useMutation
});
api[`use${capitalize(endpointName)}Mutation`] = useMutation;
}
}
};
}
};
};
// src/query/react/index.ts
__reExport(react_exports, require("@reduxjs/toolkit/query"), module.exports);
// src/query/react/ApiProvider.tsx
var import_toolkit4 = require("@reduxjs/toolkit");
var import_react4 = require("react");
var import_react5 = require("react");
var React = __toESM(require("react"));
var import_react_redux4 = require("react-redux");
var import_query2 = require("@reduxjs/toolkit/query");
function ApiProvider(props) {
const context = props.context || import_react_redux4.ReactReduxContext;
const existingContext = (0, import_react4.useContext)(context);
if (existingContext) {
throw new Error(false ? _formatProdErrorMessage4(35) : "Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.");
}
const [store] = React.useState(() => (0, import_toolkit4.configureStore)({
reducer: {
[props.api.reducerPath]: props.api.reducer
},
middleware: (gDM) => gDM().concat(props.api.middleware)
}));
(0, import_react5.useEffect)(() => props.setupListeners === false ? void 0 : (0, import_query2.setupListeners)(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);
return /* @__PURE__ */ React.createElement(import_react_redux4.Provider, { store, context }, props.children);
}
// src/query/react/index.ts
var createApi = /* @__PURE__ */ (0, import_query3.buildCreateApi)((0, import_query3.coreModule)(), reactHooksModule());
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ApiProvider,
UNINITIALIZED_VALUE,
createApi,
reactHooksModule,
reactHooksModuleName,
...require("@reduxjs/toolkit/query")
});
//# sourceMappingURL=rtk-query-react.development.cjs.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,501 @@
import * as _reduxjs_toolkit_query from '@reduxjs/toolkit/query';
import { QueryDefinition, MutationDefinition, QueryArgFrom, SkipToken, BaseQueryFn, SubscriptionOptions, QueryActionCreatorResult, TSHelpersNoInfer, TSHelpersId, TSHelpersOverride, QueryStatus, MutationResultSelectorResult, MutationActionCreatorResult, QuerySubState, ResultTypeFrom, EndpointDefinitions, DefinitionType, QueryKeys, PrefetchOptions, Module, Api, setupListeners } from '@reduxjs/toolkit/query';
export * from '@reduxjs/toolkit/query';
import * as react_redux from 'react-redux';
import { ReactReduxContextValue } from 'react-redux';
import { createSelector } from 'reselect';
import * as React from 'react';
import { Context } from 'react';
export declare const UNINITIALIZED_VALUE: unique symbol;
type UninitializedValue = typeof UNINITIALIZED_VALUE;
type QueryHooks<Definition extends QueryDefinition<any, any, any, any, any>> = {
useQuery: UseQuery<Definition>;
useLazyQuery: UseLazyQuery<Definition>;
useQuerySubscription: UseQuerySubscription<Definition>;
useLazyQuerySubscription: UseLazyQuerySubscription<Definition>;
useQueryState: UseQueryState<Definition>;
};
type MutationHooks<Definition extends MutationDefinition<any, any, any, any, any>> = {
useMutation: UseMutation<Definition>;
};
/**
* A React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and 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.
*
* 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, and the hook will return the data for that query arg once it's available.
*
* This hook combines the functionality of both [`useQueryState`](#usequerystate) and [`useQuerySubscription`](#usequerysubscription) together, and is intended to be used in the majority of situations.
*
* #### Features
*
* - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
type UseQuery<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions & UseQueryStateOptions<D, R>) => UseQueryHookResult<D, R>;
type TypedUseQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type UseQueryHookResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & UseQuerySubscriptionResult<D>;
/**
* Helper type to manually type the result
* of the `useQuery` hook in userland code.
*/
type TypedUseQueryHookResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> & TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>;
type UseQuerySubscriptionOptions = SubscriptionOptions & {
/**
* Prevents a query from automatically running.
*
* @remarks
* When `skip` is true (or `skipToken` is passed in as `arg`):
*
* - **If the query has cached data:**
* * 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
* * The query will have a status of `uninitialized`
* * If `skip: false` is set after the initial load, the cached result will be used
* - **If the query does not have cached data:**
* * The query will have a status of `uninitialized`
* * The query will not exist in the state when viewed with the dev tools
* * The query will not automatically fetch on mount
* * The query will not automatically run when additional components with the same query are added that do run
*
* @example
* ```tsx
* // codeblock-meta no-transpile title="Skip example"
* const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
* const { data, error, status } = useGetPokemonByNameQuery(name, {
* skip,
* });
*
* return (
* <div>
* {name} - {status}
* </div>
* );
* };
* ```
*/
skip?: boolean;
/**
* 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.
* - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
* - `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.
* - `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.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*/
refetchOnMountOrArgChange?: boolean | number;
};
/**
* A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.
*
* 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.
*
* Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).
*
* #### Features
*
* - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
*/
type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions) => UseQuerySubscriptionResult<D>;
type TypedUseQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type UseQuerySubscriptionResult<D extends QueryDefinition<any, any, any, any>> = Pick<QueryActionCreatorResult<D>, 'refetch'>;
/**
* Helper type to manually type the result
* of the `useQuerySubscription` hook in userland code.
*/
type TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscriptionResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type UseLazyQueryLastPromiseInfo<D extends QueryDefinition<any, any, any, any>> = {
lastArg: QueryArgFrom<D>;
};
/**
* A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.
*
* This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).
*
* #### Features
*
* - Manual control over firing a request to retrieve data
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
* - 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
*
* #### Note
*
* 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.
*/
type UseLazyQuery<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(options?: SubscriptionOptions & Omit<UseQueryStateOptions<D, R>, 'skip'>) => [
LazyQueryTrigger<D>,
UseQueryStateResult<D, R>,
UseLazyQueryLastPromiseInfo<D>
];
type TypedUseLazyQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {
/**
* Triggers a lazy query.
*
* By default, this will start a new request even if there is already a value in the cache.
* 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`.
*
* @remarks
* If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap with async await"
* try {
* const payload = await getUserById(1).unwrap();
* console.log('fulfilled', payload)
* } catch (error) {
* console.error('rejected', error);
* }
* ```
*/
(arg: QueryArgFrom<D>, preferCacheValue?: boolean): QueryActionCreatorResult<D>;
};
type TypedLazyQueryTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = LazyQueryTrigger<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
/**
* A React hook similar to [`useQuerySubscription`](#usequerysubscription), but with manual control over when the data fetching occurs.
*
* Note that this hook does not return a request status or cached data. For that use-case, see [`useLazyQuery`](#uselazyquery).
*
* #### Features
*
* - Manual control over firing a request to retrieve data
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - 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
*/
type UseLazyQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (options?: SubscriptionOptions) => readonly [LazyQueryTrigger<D>, QueryArgFrom<D> | UninitializedValue];
type TypedUseLazyQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type QueryStateSelector<R extends Record<string, any>, D extends QueryDefinition<any, any, any, any>> = (state: UseQueryStateDefaultResult<D>) => R;
/**
* 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.
*
* Note that this hook does not trigger fetching new data. For that use-case, see [`useQuery`](#usequery) or [`useQuerySubscription`](#usequerysubscription).
*
* #### Features
*
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
type UseQueryState<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(arg: QueryArgFrom<D> | SkipToken, options?: UseQueryStateOptions<D, R>) => UseQueryStateResult<D, R>;
type TypedUseQueryState<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQueryState<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type UseQueryStateOptions<D extends QueryDefinition<any, any, any, any>, R extends Record<string, any>> = {
/**
* Prevents a query from automatically running.
*
* @remarks
* When skip is true:
*
* - **If the query has cached data:**
* * 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
* * The query will have a status of `uninitialized`
* * If `skip: false` is set after skipping the initial load, the cached result will be used
* - **If the query does not have cached data:**
* * The query will have a status of `uninitialized`
* * The query will not exist in the state when viewed with the dev tools
* * The query will not automatically fetch on mount
* * The query will not automatically run when additional components with the same query are added that do run
*
* @example
* ```ts
* // codeblock-meta title="Skip example"
* const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
* const { data, error, status } = useGetPokemonByNameQuery(name, {
* skip,
* });
*
* return (
* <div>
* {name} - {status}
* </div>
* );
* };
* ```
*/
skip?: boolean;
/**
* `selectFromResult` allows you to get a specific segment from a query result in a performant manner.
* When using this feature, the component will not rerender unless the underlying data of the selected item has changed.
* If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
*
* @example
* ```ts
* // codeblock-meta title="Using selectFromResult to extract a single result"
* function PostsList() {
* const { data: posts } = api.useGetPostsQuery();
*
* return (
* <ul>
* {posts?.data?.map((post) => (
* <PostById key={post.id} id={post.id} />
* ))}
* </ul>
* );
* }
*
* function PostById({ id }: { id: number }) {
* // Will select the post with the given id, and will only rerender if the given posts data changes
* const { post } = api.useGetPostsQuery(undefined, {
* selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),
* });
*
* return <li>{post?.name}</li>;
* }
* ```
*/
selectFromResult?: QueryStateSelector<R, D>;
};
type UseQueryStateResult<_ extends QueryDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R>;
/**
* Helper type to manually type the result
* of the `useQueryState` hook in userland code.
*/
type TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TSHelpersNoInfer<R>;
type UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> = QuerySubState<D> & {
/**
* Where `data` tries to hold data as much as possible, also re-using
* data from the last arguments passed into the hook, this property
* will always contain the received data from the query, for the current query arguments.
*/
currentData?: ResultTypeFrom<D>;
/**
* Query has not started yet.
*/
isUninitialized: false;
/**
* Query is currently loading for the first time. No data yet.
*/
isLoading: false;
/**
* Query is currently fetching, but might have data from an earlier request.
*/
isFetching: false;
/**
* Query has data from a successful load.
*/
isSuccess: false;
/**
* Query is currently in "error" state.
*/
isError: false;
};
type UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> = TSHelpersId<TSHelpersOverride<Extract<UseQueryStateBaseResult<D>, {
status: QueryStatus.uninitialized;
}>, {
isUninitialized: true;
}> | TSHelpersOverride<UseQueryStateBaseResult<D>, {
isLoading: true;
isFetching: boolean;
data: undefined;
} | ({
isSuccess: true;
isFetching: true;
error: undefined;
} & Required<Pick<UseQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp'>>) | ({
isSuccess: true;
isFetching: false;
error: undefined;
} & Required<Pick<UseQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp' | 'currentData'>>) | ({
isError: true;
} & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>)>> & {
/**
* @deprecated Included for completeness, but discouraged.
* Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
* and `isUninitialized` flags instead
*/
status: QueryStatus;
};
type MutationStateSelector<R extends Record<string, any>, D extends MutationDefinition<any, any, any, any>> = (state: MutationResultSelectorResult<D>) => R;
type UseMutationStateOptions<D extends MutationDefinition<any, any, any, any>, R extends Record<string, any>> = {
selectFromResult?: MutationStateSelector<R, D>;
fixedCacheKey?: string;
};
type UseMutationStateResult<D extends MutationDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R> & {
originalArgs?: QueryArgFrom<D>;
/**
* Resets the hook state to its initial `uninitialized` state.
* This will also remove the last result from the cache.
*/
reset: () => void;
};
/**
* Helper type to manually type the result
* of the `useMutation` hook in userland code.
*/
type TypedUseMutationResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = MutationResultSelectorResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseMutationStateResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;
/**
* 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.
*
* #### Features
*
* - Manual control over firing a request to alter data on the server or possibly invalidate the cache
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
type UseMutation<D extends MutationDefinition<any, any, any, any>> = <R extends Record<string, any> = MutationResultSelectorResult<D>>(options?: UseMutationStateOptions<D, R>) => readonly [MutationTrigger<D>, UseMutationStateResult<D, R>];
type TypedUseMutation<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseMutation<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type MutationTrigger<D extends MutationDefinition<any, any, any, any>> = {
/**
* Triggers the mutation and returns a Promise.
* @remarks
* If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap with async await"
* try {
* const payload = await addPost({ id: 1, name: 'Example' }).unwrap();
* console.log('fulfilled', payload)
* } catch (error) {
* console.error('rejected', error);
* }
* ```
*/
(arg: QueryArgFrom<D>): MutationActionCreatorResult<D>;
};
type TypedMutationTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = MutationTrigger<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type QueryHookNames<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions as Definitions[K] extends {
type: DefinitionType.query;
} ? `use${Capitalize<K & string>}Query` : never]: UseQuery<Extract<Definitions[K], QueryDefinition<any, any, any, any>>>;
};
type LazyQueryHookNames<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions as Definitions[K] extends {
type: DefinitionType.query;
} ? `useLazy${Capitalize<K & string>}Query` : never]: UseLazyQuery<Extract<Definitions[K], QueryDefinition<any, any, any, any>>>;
};
type MutationHookNames<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions as Definitions[K] extends {
type: DefinitionType.mutation;
} ? `use${Capitalize<K & string>}Mutation` : never]: UseMutation<Extract<Definitions[K], MutationDefinition<any, any, any, any>>>;
};
type HooksWithUniqueNames<Definitions extends EndpointDefinitions> = QueryHookNames<Definitions> & LazyQueryHookNames<Definitions> & MutationHookNames<Definitions>;
export declare const reactHooksModuleName: unique symbol;
type ReactHooksModule = typeof reactHooksModuleName;
declare module '@reduxjs/toolkit/query' {
interface ApiModules<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {
[reactHooksModuleName]: {
/**
* Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.
*/
endpoints: {
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? QueryHooks<Definitions[K]> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? MutationHooks<Definitions[K]> : never;
};
/**
* A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.
*/
usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, options?: PrefetchOptions): (arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions) => void;
} & HooksWithUniqueNames<Definitions>;
}
}
type RR = typeof react_redux;
interface ReactHooksModuleOptions {
/**
* The hooks from React Redux to be used
*/
hooks?: {
/**
* The version of the `useDispatch` hook to be used
*/
useDispatch: RR['useDispatch'];
/**
* The version of the `useSelector` hook to be used
*/
useSelector: RR['useSelector'];
/**
* The version of the `useStore` hook to be used
*/
useStore: RR['useStore'];
};
/**
* The version of the `batchedUpdates` function to be used
*/
batch?: RR['batch'];
/**
* Enables performing asynchronous tasks immediately within a render.
*
* @example
*
* ```ts
* import {
* buildCreateApi,
* coreModule,
* reactHooksModule
* } from '@reduxjs/toolkit/query/react'
*
* const createApi = buildCreateApi(
* coreModule(),
* reactHooksModule({ unstable__sideEffectsInRender: true })
* )
* ```
*/
unstable__sideEffectsInRender?: boolean;
/**
* A selector creator (usually from `reselect`, or matching the same signature)
*/
createSelector?: typeof createSelector;
}
/**
* Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.
*
* @example
* ```ts
* const MyContext = React.createContext<ReactReduxContextValue | null>(null);
* const customCreateApi = buildCreateApi(
* coreModule(),
* reactHooksModule({
* hooks: {
* useDispatch: createDispatchHook(MyContext),
* useSelector: createSelectorHook(MyContext),
* useStore: createStoreHook(MyContext)
* }
* })
* );
* ```
*
* @returns A module for use with `buildCreateApi`
*/
declare const reactHooksModule: ({ batch, hooks, createSelector, unstable__sideEffectsInRender, ...rest }?: ReactHooksModuleOptions) => Module<ReactHooksModule>;
/**
* Can be used as a `Provider` if you **do not already have a Redux store**.
*
* @example
* ```tsx
* // codeblock-meta no-transpile title="Basic usage - wrap your App with ApiProvider"
* import * as React from 'react';
* import { ApiProvider } from '@reduxjs/toolkit/query/react';
* import { Pokemon } from './features/Pokemon';
*
* function App() {
* return (
* <ApiProvider api={api}>
* <Pokemon />
* </ApiProvider>
* );
* }
* ```
*
* @remarks
* Using this together with an existing redux store, both will
* conflict with each other - please use the traditional redux setup
* in that case.
*/
declare function ApiProvider(props: {
children: any;
api: Api<any, {}, any, any>;
setupListeners?: Parameters<typeof setupListeners>[1] | false;
context?: Context<ReactReduxContextValue | null>;
}): React.JSX.Element;
declare const createApi: _reduxjs_toolkit_query.CreateApi<typeof _reduxjs_toolkit_query.coreModuleName | typeof reactHooksModuleName>;
export { ApiProvider, type TypedLazyQueryTrigger, type TypedMutationTrigger, type TypedUseLazyQuery, type TypedUseLazyQuerySubscription, type TypedUseMutation, type TypedUseMutationResult, type TypedUseQuery, type TypedUseQueryHookResult, type TypedUseQueryState, type TypedUseQueryStateResult, type TypedUseQuerySubscription, type TypedUseQuerySubscriptionResult, createApi, reactHooksModule };

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,642 @@
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
var target = {};
for (var prop in source)
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
target[prop] = source[prop];
if (source != null && __getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(source)) {
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
target[prop] = source[prop];
}
return target;
};
// src/query/react/index.ts
import { buildCreateApi, coreModule } from "@reduxjs/toolkit/query";
// src/query/react/module.ts
import { formatProdErrorMessage as _formatProdErrorMessage3 } from "@reduxjs/toolkit";
import { batch as rrBatch, useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore } from "react-redux";
import { createSelector as _createSelector } from "reselect";
// src/query/endpointDefinitions.ts
function isQueryDefinition(e) {
return e.type === "query" /* query */;
}
function isMutationDefinition(e) {
return e.type === "mutation" /* mutation */;
}
// src/query/tsHelpers.ts
function safeAssign(target, ...args) {
return Object.assign(target, ...args);
}
// src/query/utils/capitalize.ts
function capitalize(str) {
return str.replace(str[0], str[0].toUpperCase());
}
// src/query/core/rtkImports.ts
import { createAction, createSlice, createSelector, createAsyncThunk, combineReducers, createNextState, isAnyOf, isAllOf, isAction, isPending, isRejected, isFulfilled, isRejectedWithValue, isAsyncThunkAction, prepareAutoBatched, SHOULD_AUTOBATCH, isPlainObject, nanoid } from "@reduxjs/toolkit";
// src/query/utils/countObjectKeys.ts
function countObjectKeys(obj) {
let count = 0;
for (const _key in obj) {
count++;
}
return count;
}
// src/query/react/buildHooks.ts
import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2 } from "@reduxjs/toolkit";
import { QueryStatus, skipToken } from "@reduxjs/toolkit/query";
import { useCallback, useDebugValue, useEffect as useEffect3, useLayoutEffect, useMemo as useMemo2, useRef as useRef3, useState } from "react";
import { shallowEqual as shallowEqual2 } from "react-redux";
// src/query/defaultSerializeQueryArgs.ts
var cache = WeakMap ? /* @__PURE__ */ new WeakMap() : void 0;
var defaultSerializeQueryArgs = ({
endpointName,
queryArgs
}) => {
let serialized = "";
const cached = cache == null ? void 0 : cache.get(queryArgs);
if (typeof cached === "string") {
serialized = cached;
} else {
const stringified = JSON.stringify(queryArgs, (key, value) => {
value = typeof value === "bigint" ? {
$bigint: value.toString()
} : value;
value = isPlainObject(value) ? Object.keys(value).sort().reduce((acc, key2) => {
acc[key2] = value[key2];
return acc;
}, {}) : value;
return value;
});
if (isPlainObject(queryArgs)) {
cache == null ? void 0 : cache.set(queryArgs, stringified);
}
serialized = stringified;
}
return `${endpointName}(${serialized})`;
};
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/useSerializedStableValue.ts
import { useEffect, useRef, useMemo } from "react";
function useStableQueryArgs(queryArgs, serialize, endpointDefinition, endpointName) {
const incoming = useMemo(() => ({
queryArgs,
serialized: typeof queryArgs == "object" ? serialize({
queryArgs,
endpointDefinition,
endpointName
}) : queryArgs
}), [queryArgs, serialize, endpointDefinition, endpointName]);
const cache2 = useRef(incoming);
useEffect(() => {
if (cache2.current.serialized !== incoming.serialized) {
cache2.current = incoming;
}
}, [incoming]);
return cache2.current.serialized === incoming.serialized ? cache2.current.queryArgs : queryArgs;
}
// src/query/react/useShallowStableValue.ts
import { useEffect as useEffect2, useRef as useRef2 } from "react";
import { shallowEqual } from "react-redux";
function useShallowStableValue(value) {
const cache2 = useRef2(value);
useEffect2(() => {
if (!shallowEqual(cache2.current, value)) {
cache2.current = value;
}
}, [value]);
return shallowEqual(cache2.current, value) ? cache2.current : value;
}
// src/query/react/buildHooks.ts
var canUseDOM = () => !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
var isDOM = /* @__PURE__ */ canUseDOM();
var isRunningInReactNative = () => typeof navigator !== "undefined" && navigator.product === "ReactNative";
var isReactNative = /* @__PURE__ */ isRunningInReactNative();
var getUseIsomorphicLayoutEffect = () => isDOM || isReactNative ? useLayoutEffect : useEffect3;
var useIsomorphicLayoutEffect = /* @__PURE__ */ getUseIsomorphicLayoutEffect();
var noPendingQueryStateSelector = (selected) => {
if (selected.isUninitialized) {
return __spreadProps(__spreadValues({}, selected), {
isUninitialized: false,
isFetching: true,
isLoading: selected.data !== void 0 ? false : true,
status: QueryStatus.pending
});
}
return selected;
};
function buildHooks({
api,
moduleOptions: {
batch,
hooks: {
useDispatch,
useSelector,
useStore
},
unstable__sideEffectsInRender,
createSelector: createSelector2
},
serializeQueryArgs,
context
}) {
const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : useEffect3;
return {
buildQueryHooks,
buildMutationHook,
usePrefetch
};
function queryStatePreSelector(currentState, lastResult, queryArgs) {
if ((lastResult == null ? void 0 : lastResult.endpointName) && currentState.isUninitialized) {
const {
endpointName
} = lastResult;
const endpointDefinition = context.endpointDefinitions[endpointName];
if (serializeQueryArgs({
queryArgs: lastResult.originalArgs,
endpointDefinition,
endpointName
}) === serializeQueryArgs({
queryArgs,
endpointDefinition,
endpointName
})) lastResult = void 0;
}
let data = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data;
if (data === void 0) data = currentState.data;
const hasData = data !== void 0;
const isFetching = currentState.isLoading;
const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;
const isSuccess = currentState.isSuccess || isFetching && hasData;
return __spreadProps(__spreadValues({}, 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, __spreadValues(__spreadValues({}, stableDefaultOptions), options))), [endpointName, dispatch, stableDefaultOptions]);
}
function buildQueryHooks(name) {
const useQuerySubscription = (arg, {
refetchOnReconnect,
refetchOnFocus,
refetchOnMountOrArgChange,
skip = false,
pollingInterval = 0,
skipPollingIfUnfocused = false
} = {}) => {
const {
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const subscriptionSelectorsRef = useRef3(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 ? 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,
// Even if the user provided a per-endpoint `serializeQueryArgs` with
// a consistent return value, _here_ we want to use the default behavior
// so we can tell if _anything_ actually changed. Otherwise, we can end up
// with a case where the query args did change but the serialization doesn't,
// and then we never try to initiate a refetch.
defaultSerializeQueryArgs,
context.endpointDefinitions[name],
name
);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval,
skipPollingIfUnfocused
});
const lastRenderHadSubscription = useRef3(false);
const promiseRef = useRef3(void 0);
let {
queryCacheKey,
requestId
} = promiseRef.current || {};
let currentRenderHasSubscription = false;
if (queryCacheKey && requestId) {
currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(queryCacheKey, requestId);
}
const subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;
usePossiblyImmediateEffect(() => {
lastRenderHadSubscription.current = currentRenderHasSubscription;
});
usePossiblyImmediateEffect(() => {
if (subscriptionRemoved) {
promiseRef.current = void 0;
}
}, [subscriptionRemoved]);
usePossiblyImmediateEffect(() => {
var _a;
const lastPromise = promiseRef.current;
if (typeof process !== "undefined" && process.env.NODE_ENV === "removeMeOnCompilation") {
console.log(subscriptionRemoved);
}
if (stableArg === skipToken) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
promiseRef.current = void 0;
return;
}
const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (!lastPromise || lastPromise.arg !== stableArg) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
const promise = dispatch(initiate(stableArg, {
subscriptionOptions: stableSubscriptionOptions,
forceRefetch: refetchOnMountOrArgChange
}));
promiseRef.current = promise;
} else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved]);
useEffect3(() => {
return () => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return useMemo2(() => ({
/**
* A method to manually refetch data for the query
*/
refetch: () => {
var _a;
if (!promiseRef.current) throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage2(38) : "Cannot refetch a query that has not been started yet.");
return (_a = promiseRef.current) == null ? void 0 : _a.refetch();
}
}), []);
};
const useLazyQuerySubscription = ({
refetchOnReconnect,
refetchOnFocus,
pollingInterval = 0,
skipPollingIfUnfocused = false
} = {}) => {
const {
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const [arg, setArg] = useState(UNINITIALIZED_VALUE);
const promiseRef = useRef3(void 0);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval,
skipPollingIfUnfocused
});
usePossiblyImmediateEffect(() => {
var _a, _b;
const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (stableSubscriptionOptions !== lastSubscriptionOptions) {
(_b = promiseRef.current) == null ? void 0 : _b.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [stableSubscriptionOptions]);
const subscriptionOptionsRef = useRef3(stableSubscriptionOptions);
usePossiblyImmediateEffect(() => {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
const trigger = useCallback(function(arg2, preferCacheValue = false) {
let promise;
batch(() => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = promise = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
return promise;
}, [dispatch, initiate]);
useEffect3(() => {
return () => {
var _a;
(_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
};
}, []);
useEffect3(() => {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return useMemo2(() => [trigger, arg], [trigger, arg]);
};
const useQueryState = (arg, {
skip = false,
selectFromResult
} = {}) => {
const {
select
} = api.endpoints[name];
const stableArg = useStableQueryArgs(skip ? skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);
const lastValue = useRef3(void 0);
const selectDefaultResult = useMemo2(() => createSelector2([select(stableArg), (_, lastResult) => lastResult, (_) => stableArg], queryStatePreSelector, {
memoizeOptions: {
resultEqualityCheck: shallowEqual2
}
}), [select, stableArg]);
const querySelector = useMemo2(() => selectFromResult ? createSelector2([selectDefaultResult], selectFromResult, {
devModeChecks: {
identityFunctionCheck: "never"
}
}) : selectDefaultResult, [selectDefaultResult, selectFromResult]);
const currentState = useSelector((state) => querySelector(state, lastValue.current), shallowEqual2);
const store = useStore();
const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
useIsomorphicLayoutEffect(() => {
lastValue.current = newLastValue;
}, [newLastValue]);
return currentState;
};
return {
useQueryState,
useQuerySubscription,
useLazyQuerySubscription,
useLazyQuery(options) {
const [trigger, arg] = useLazyQuerySubscription(options);
const queryStateResults = useQueryState(arg, __spreadProps(__spreadValues({}, options), {
skip: arg === UNINITIALIZED_VALUE
}));
const info = useMemo2(() => ({
lastArg: arg
}), [arg]);
return useMemo2(() => [trigger, queryStateResults, info], [trigger, queryStateResults, info]);
},
useQuery(arg, options) {
const querySubscriptionResults = useQuerySubscription(arg, options);
const queryStateResults = useQueryState(arg, __spreadValues({
selectFromResult: arg === skipToken || (options == null ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector
}, options));
const {
data,
status,
isLoading,
isSuccess,
isError,
error
} = queryStateResults;
useDebugValue({
data,
status,
isLoading,
isSuccess,
isError,
error
});
return useMemo2(() => __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults), [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return ({
selectFromResult,
fixedCacheKey
} = {}) => {
const {
select,
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const [promise, setPromise] = useState();
useEffect3(() => () => {
if (!(promise == null ? void 0 : promise.arg.fixedCacheKey)) {
promise == null ? void 0 : promise.reset();
}
}, [promise]);
const triggerMutation = useCallback(function(arg) {
const promise2 = dispatch(initiate(arg, {
fixedCacheKey
}));
setPromise(promise2);
return promise2;
}, [dispatch, initiate, fixedCacheKey]);
const {
requestId
} = promise || {};
const selectDefaultResult = useMemo2(() => select({
fixedCacheKey,
requestId: promise == null ? void 0 : promise.requestId
}), [fixedCacheKey, promise, select]);
const mutationSelector = useMemo2(() => selectFromResult ? createSelector2([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]);
const currentState = useSelector(mutationSelector, shallowEqual2);
const originalArgs = fixedCacheKey == null ? promise == null ? 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 {
endpointName,
data,
status,
isLoading,
isSuccess,
isError,
error
} = currentState;
useDebugValue({
endpointName,
data,
status,
isLoading,
isSuccess,
isError,
error
});
const finalState = useMemo2(() => __spreadProps(__spreadValues({}, currentState), {
originalArgs,
reset
}), [currentState, originalArgs, reset]);
return useMemo2(() => [triggerMutation, finalState], [triggerMutation, finalState]);
};
}
}
// src/query/react/module.ts
var reactHooksModuleName = /* @__PURE__ */ Symbol();
var reactHooksModule = (_a = {}) => {
var _b = _a, {
batch = rrBatch,
hooks = {
useDispatch: rrUseDispatch,
useSelector: rrUseSelector,
useStore: rrUseStore
},
createSelector: createSelector2 = _createSelector,
unstable__sideEffectsInRender = false
} = _b, rest = __objRest(_b, [
"batch",
"hooks",
"createSelector",
"unstable__sideEffectsInRender"
]);
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" ? _formatProdErrorMessage3(36) : `When using custom hooks for context, all ${hookNames.length} hooks need to be provided: ${hookNames.join(", ")}.
Hook ${hookName} was either not provided or not a function.`);
}
}
}
return {
name: reactHooksModuleName,
init(api, {
serializeQueryArgs
}, context) {
const anyApi = api;
const {
buildQueryHooks,
buildMutationHook,
usePrefetch
} = buildHooks({
api,
moduleOptions: {
batch,
hooks,
unstable__sideEffectsInRender,
createSelector: createSelector2
},
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;
} else if (isMutationDefinition(definition)) {
const useMutation = buildMutationHook(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useMutation
});
api[`use${capitalize(endpointName)}Mutation`] = useMutation;
}
}
};
}
};
};
// src/query/react/index.ts
export * from "@reduxjs/toolkit/query";
// src/query/react/ApiProvider.tsx
import { configureStore, formatProdErrorMessage as _formatProdErrorMessage4 } from "@reduxjs/toolkit";
import { useContext } from "react";
import { useEffect as useEffect4 } from "react";
import * as React from "react";
import { Provider, ReactReduxContext } from "react-redux";
import { setupListeners } from "@reduxjs/toolkit/query";
function ApiProvider(props) {
const context = props.context || ReactReduxContext;
const existingContext = useContext(context);
if (existingContext) {
throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage4(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)
}));
useEffect4(() => props.setupListeners === false ? void 0 : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);
return /* @__PURE__ */ React.createElement(Provider, { store, context }, props.children);
}
// src/query/react/index.ts
var createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule());
export {
ApiProvider,
UNINITIALIZED_VALUE,
createApi,
reactHooksModule,
reactHooksModuleName
};
//# sourceMappingURL=rtk-query-react.legacy-esm.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,610 @@
// src/query/react/index.ts
import { buildCreateApi, coreModule } from "@reduxjs/toolkit/query";
// src/query/react/module.ts
import { formatProdErrorMessage as _formatProdErrorMessage3 } from "@reduxjs/toolkit";
import { batch as rrBatch, useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore } from "react-redux";
import { createSelector as _createSelector } from "reselect";
// src/query/endpointDefinitions.ts
function isQueryDefinition(e) {
return e.type === "query" /* query */;
}
function isMutationDefinition(e) {
return e.type === "mutation" /* mutation */;
}
// src/query/tsHelpers.ts
function safeAssign(target, ...args) {
return Object.assign(target, ...args);
}
// src/query/utils/capitalize.ts
function capitalize(str) {
return str.replace(str[0], str[0].toUpperCase());
}
// src/query/core/rtkImports.ts
import { createAction, createSlice, createSelector, createAsyncThunk, combineReducers, createNextState, isAnyOf, isAllOf, isAction, isPending, isRejected, isFulfilled, isRejectedWithValue, isAsyncThunkAction, prepareAutoBatched, SHOULD_AUTOBATCH, isPlainObject, nanoid } from "@reduxjs/toolkit";
// src/query/utils/countObjectKeys.ts
function countObjectKeys(obj) {
let count = 0;
for (const _key in obj) {
count++;
}
return count;
}
// src/query/react/buildHooks.ts
import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2 } from "@reduxjs/toolkit";
import { QueryStatus, skipToken } from "@reduxjs/toolkit/query";
import { useCallback, useDebugValue, useEffect as useEffect3, useLayoutEffect, useMemo as useMemo2, useRef as useRef3, useState } from "react";
import { shallowEqual as shallowEqual2 } from "react-redux";
// src/query/defaultSerializeQueryArgs.ts
var cache = WeakMap ? /* @__PURE__ */ new WeakMap() : void 0;
var defaultSerializeQueryArgs = ({
endpointName,
queryArgs
}) => {
let serialized = "";
const cached = cache?.get(queryArgs);
if (typeof cached === "string") {
serialized = cached;
} else {
const stringified = JSON.stringify(queryArgs, (key, value) => {
value = typeof value === "bigint" ? {
$bigint: value.toString()
} : value;
value = isPlainObject(value) ? Object.keys(value).sort().reduce((acc, key2) => {
acc[key2] = value[key2];
return acc;
}, {}) : value;
return value;
});
if (isPlainObject(queryArgs)) {
cache?.set(queryArgs, stringified);
}
serialized = stringified;
}
return `${endpointName}(${serialized})`;
};
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/useSerializedStableValue.ts
import { useEffect, useRef, useMemo } from "react";
function useStableQueryArgs(queryArgs, serialize, endpointDefinition, endpointName) {
const incoming = useMemo(() => ({
queryArgs,
serialized: typeof queryArgs == "object" ? serialize({
queryArgs,
endpointDefinition,
endpointName
}) : queryArgs
}), [queryArgs, serialize, endpointDefinition, endpointName]);
const cache2 = useRef(incoming);
useEffect(() => {
if (cache2.current.serialized !== incoming.serialized) {
cache2.current = incoming;
}
}, [incoming]);
return cache2.current.serialized === incoming.serialized ? cache2.current.queryArgs : queryArgs;
}
// src/query/react/useShallowStableValue.ts
import { useEffect as useEffect2, useRef as useRef2 } from "react";
import { shallowEqual } from "react-redux";
function useShallowStableValue(value) {
const cache2 = useRef2(value);
useEffect2(() => {
if (!shallowEqual(cache2.current, value)) {
cache2.current = value;
}
}, [value]);
return shallowEqual(cache2.current, value) ? cache2.current : value;
}
// src/query/react/buildHooks.ts
var canUseDOM = () => !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
var isDOM = /* @__PURE__ */ canUseDOM();
var isRunningInReactNative = () => typeof navigator !== "undefined" && navigator.product === "ReactNative";
var isReactNative = /* @__PURE__ */ isRunningInReactNative();
var getUseIsomorphicLayoutEffect = () => isDOM || isReactNative ? useLayoutEffect : useEffect3;
var useIsomorphicLayoutEffect = /* @__PURE__ */ getUseIsomorphicLayoutEffect();
var noPendingQueryStateSelector = (selected) => {
if (selected.isUninitialized) {
return {
...selected,
isUninitialized: false,
isFetching: true,
isLoading: selected.data !== void 0 ? false : true,
status: QueryStatus.pending
};
}
return selected;
};
function buildHooks({
api,
moduleOptions: {
batch,
hooks: {
useDispatch,
useSelector,
useStore
},
unstable__sideEffectsInRender,
createSelector: createSelector2
},
serializeQueryArgs,
context
}) {
const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : useEffect3;
return {
buildQueryHooks,
buildMutationHook,
usePrefetch
};
function queryStatePreSelector(currentState, lastResult, queryArgs) {
if (lastResult?.endpointName && currentState.isUninitialized) {
const {
endpointName
} = lastResult;
const endpointDefinition = context.endpointDefinitions[endpointName];
if (serializeQueryArgs({
queryArgs: lastResult.originalArgs,
endpointDefinition,
endpointName
}) === serializeQueryArgs({
queryArgs,
endpointDefinition,
endpointName
})) lastResult = void 0;
}
let data = currentState.isSuccess ? currentState.data : lastResult?.data;
if (data === void 0) data = currentState.data;
const hasData = data !== void 0;
const isFetching = currentState.isLoading;
const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;
const isSuccess = currentState.isSuccess || isFetching && hasData;
return {
...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, {
...stableDefaultOptions,
...options
})), [endpointName, dispatch, stableDefaultOptions]);
}
function buildQueryHooks(name) {
const useQuerySubscription = (arg, {
refetchOnReconnect,
refetchOnFocus,
refetchOnMountOrArgChange,
skip = false,
pollingInterval = 0,
skipPollingIfUnfocused = false
} = {}) => {
const {
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const subscriptionSelectorsRef = useRef3(void 0);
if (!subscriptionSelectorsRef.current) {
const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());
if (process.env.NODE_ENV !== "production") {
if (typeof returnedValue !== "object" || typeof 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,
// Even if the user provided a per-endpoint `serializeQueryArgs` with
// a consistent return value, _here_ we want to use the default behavior
// so we can tell if _anything_ actually changed. Otherwise, we can end up
// with a case where the query args did change but the serialization doesn't,
// and then we never try to initiate a refetch.
defaultSerializeQueryArgs,
context.endpointDefinitions[name],
name
);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval,
skipPollingIfUnfocused
});
const lastRenderHadSubscription = useRef3(false);
const promiseRef = useRef3(void 0);
let {
queryCacheKey,
requestId
} = promiseRef.current || {};
let currentRenderHasSubscription = false;
if (queryCacheKey && requestId) {
currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(queryCacheKey, requestId);
}
const subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;
usePossiblyImmediateEffect(() => {
lastRenderHadSubscription.current = currentRenderHasSubscription;
});
usePossiblyImmediateEffect(() => {
if (subscriptionRemoved) {
promiseRef.current = void 0;
}
}, [subscriptionRemoved]);
usePossiblyImmediateEffect(() => {
const lastPromise = promiseRef.current;
if (typeof process !== "undefined" && process.env.NODE_ENV === "removeMeOnCompilation") {
console.log(subscriptionRemoved);
}
if (stableArg === 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
}));
promiseRef.current = promise;
} else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved]);
useEffect3(() => {
return () => {
promiseRef.current?.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return useMemo2(() => ({
/**
* A method to manually refetch data for the query
*/
refetch: () => {
if (!promiseRef.current) throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage2(38) : "Cannot refetch a query that has not been started yet.");
return promiseRef.current?.refetch();
}
}), []);
};
const useLazyQuerySubscription = ({
refetchOnReconnect,
refetchOnFocus,
pollingInterval = 0,
skipPollingIfUnfocused = false
} = {}) => {
const {
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const [arg, setArg] = useState(UNINITIALIZED_VALUE);
const promiseRef = useRef3(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 = useRef3(stableSubscriptionOptions);
usePossiblyImmediateEffect(() => {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
const trigger = useCallback(function(arg2, preferCacheValue = false) {
let promise;
batch(() => {
promiseRef.current?.unsubscribe();
promiseRef.current = promise = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
return promise;
}, [dispatch, initiate]);
useEffect3(() => {
return () => {
promiseRef?.current?.unsubscribe();
};
}, []);
useEffect3(() => {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return useMemo2(() => [trigger, arg], [trigger, arg]);
};
const useQueryState = (arg, {
skip = false,
selectFromResult
} = {}) => {
const {
select
} = api.endpoints[name];
const stableArg = useStableQueryArgs(skip ? skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);
const lastValue = useRef3(void 0);
const selectDefaultResult = useMemo2(() => createSelector2([select(stableArg), (_, lastResult) => lastResult, (_) => stableArg], queryStatePreSelector, {
memoizeOptions: {
resultEqualityCheck: shallowEqual2
}
}), [select, stableArg]);
const querySelector = useMemo2(() => selectFromResult ? createSelector2([selectDefaultResult], selectFromResult, {
devModeChecks: {
identityFunctionCheck: "never"
}
}) : selectDefaultResult, [selectDefaultResult, selectFromResult]);
const currentState = useSelector((state) => querySelector(state, lastValue.current), shallowEqual2);
const store = useStore();
const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
useIsomorphicLayoutEffect(() => {
lastValue.current = newLastValue;
}, [newLastValue]);
return currentState;
};
return {
useQueryState,
useQuerySubscription,
useLazyQuerySubscription,
useLazyQuery(options) {
const [trigger, arg] = useLazyQuerySubscription(options);
const queryStateResults = useQueryState(arg, {
...options,
skip: arg === UNINITIALIZED_VALUE
});
const info = useMemo2(() => ({
lastArg: arg
}), [arg]);
return useMemo2(() => [trigger, queryStateResults, info], [trigger, queryStateResults, info]);
},
useQuery(arg, options) {
const querySubscriptionResults = useQuerySubscription(arg, options);
const queryStateResults = useQueryState(arg, {
selectFromResult: arg === skipToken || options?.skip ? void 0 : noPendingQueryStateSelector,
...options
});
const {
data,
status,
isLoading,
isSuccess,
isError,
error
} = queryStateResults;
useDebugValue({
data,
status,
isLoading,
isSuccess,
isError,
error
});
return useMemo2(() => ({
...queryStateResults,
...querySubscriptionResults
}), [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return ({
selectFromResult,
fixedCacheKey
} = {}) => {
const {
select,
initiate
} = api.endpoints[name];
const dispatch = useDispatch();
const [promise, setPromise] = useState();
useEffect3(() => () => {
if (!promise?.arg.fixedCacheKey) {
promise?.reset();
}
}, [promise]);
const triggerMutation = useCallback(function(arg) {
const promise2 = dispatch(initiate(arg, {
fixedCacheKey
}));
setPromise(promise2);
return promise2;
}, [dispatch, initiate, fixedCacheKey]);
const {
requestId
} = promise || {};
const selectDefaultResult = useMemo2(() => select({
fixedCacheKey,
requestId: promise?.requestId
}), [fixedCacheKey, promise, select]);
const mutationSelector = useMemo2(() => selectFromResult ? createSelector2([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]);
const currentState = useSelector(mutationSelector, shallowEqual2);
const originalArgs = fixedCacheKey == null ? 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 {
endpointName,
data,
status,
isLoading,
isSuccess,
isError,
error
} = currentState;
useDebugValue({
endpointName,
data,
status,
isLoading,
isSuccess,
isError,
error
});
const finalState = useMemo2(() => ({
...currentState,
originalArgs,
reset
}), [currentState, originalArgs, reset]);
return useMemo2(() => [triggerMutation, finalState], [triggerMutation, finalState]);
};
}
}
// src/query/react/module.ts
var reactHooksModuleName = /* @__PURE__ */ Symbol();
var reactHooksModule = ({
batch = rrBatch,
hooks = {
useDispatch: rrUseDispatch,
useSelector: rrUseSelector,
useStore: rrUseStore
},
createSelector: createSelector2 = _createSelector,
unstable__sideEffectsInRender = false,
...rest
} = {}) => {
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" ? _formatProdErrorMessage3(36) : `When using custom hooks for context, all ${hookNames.length} hooks need to be provided: ${hookNames.join(", ")}.
Hook ${hookName} was either not provided or not a function.`);
}
}
}
return {
name: reactHooksModuleName,
init(api, {
serializeQueryArgs
}, context) {
const anyApi = api;
const {
buildQueryHooks,
buildMutationHook,
usePrefetch
} = buildHooks({
api,
moduleOptions: {
batch,
hooks,
unstable__sideEffectsInRender,
createSelector: createSelector2
},
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;
} else if (isMutationDefinition(definition)) {
const useMutation = buildMutationHook(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useMutation
});
api[`use${capitalize(endpointName)}Mutation`] = useMutation;
}
}
};
}
};
};
// src/query/react/index.ts
export * from "@reduxjs/toolkit/query";
// src/query/react/ApiProvider.tsx
import { configureStore, formatProdErrorMessage as _formatProdErrorMessage4 } from "@reduxjs/toolkit";
import { useContext } from "react";
import { useEffect as useEffect4 } from "react";
import * as React from "react";
import { Provider, ReactReduxContext } from "react-redux";
import { setupListeners } from "@reduxjs/toolkit/query";
function ApiProvider(props) {
const context = props.context || ReactReduxContext;
const existingContext = useContext(context);
if (existingContext) {
throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage4(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)
}));
useEffect4(() => props.setupListeners === false ? void 0 : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);
return /* @__PURE__ */ React.createElement(Provider, { store, context }, props.children);
}
// src/query/react/index.ts
var createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule());
export {
ApiProvider,
UNINITIALIZED_VALUE,
createApi,
reactHooksModule,
reactHooksModuleName
};
//# sourceMappingURL=rtk-query-react.modern.mjs.map

File diff suppressed because one or more lines are too long