rtk-query-react.modern.development.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. var __defProp = Object.defineProperty;
  2. var __defProps = Object.defineProperties;
  3. var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
  4. var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  5. var __hasOwnProp = Object.prototype.hasOwnProperty;
  6. var __propIsEnum = Object.prototype.propertyIsEnumerable;
  7. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  8. var __spreadValues = (a, b) => {
  9. for (var prop in b || (b = {}))
  10. if (__hasOwnProp.call(b, prop))
  11. __defNormalProp(a, prop, b[prop]);
  12. if (__getOwnPropSymbols)
  13. for (var prop of __getOwnPropSymbols(b)) {
  14. if (__propIsEnum.call(b, prop))
  15. __defNormalProp(a, prop, b[prop]);
  16. }
  17. return a;
  18. };
  19. var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
  20. // src/query/react/index.ts
  21. import { coreModule, buildCreateApi } from "@reduxjs/toolkit/query";
  22. // src/query/react/buildHooks.ts
  23. import { createSelector } from "@reduxjs/toolkit";
  24. import { useCallback, useDebugValue, useEffect as useEffect3, useLayoutEffect, useMemo as useMemo2, useRef as useRef3, useState } from "react";
  25. import { QueryStatus, skipToken } from "@reduxjs/toolkit/query";
  26. import { shallowEqual as shallowEqual2 } from "react-redux";
  27. // src/query/react/useSerializedStableValue.ts
  28. import { useEffect, useRef, useMemo } from "react";
  29. function useStableQueryArgs(queryArgs, serialize, endpointDefinition, endpointName) {
  30. const incoming = useMemo(() => ({
  31. queryArgs,
  32. serialized: typeof queryArgs == "object" ? serialize({ queryArgs, endpointDefinition, endpointName }) : queryArgs
  33. }), [queryArgs, serialize, endpointDefinition, endpointName]);
  34. const cache2 = useRef(incoming);
  35. useEffect(() => {
  36. if (cache2.current.serialized !== incoming.serialized) {
  37. cache2.current = incoming;
  38. }
  39. }, [incoming]);
  40. return cache2.current.serialized === incoming.serialized ? cache2.current.queryArgs : queryArgs;
  41. }
  42. // src/query/react/constants.ts
  43. var UNINITIALIZED_VALUE = Symbol();
  44. // src/query/react/useShallowStableValue.ts
  45. import { useEffect as useEffect2, useRef as useRef2 } from "react";
  46. import { shallowEqual } from "react-redux";
  47. function useShallowStableValue(value) {
  48. const cache2 = useRef2(value);
  49. useEffect2(() => {
  50. if (!shallowEqual(cache2.current, value)) {
  51. cache2.current = value;
  52. }
  53. }, [value]);
  54. return shallowEqual(cache2.current, value) ? cache2.current : value;
  55. }
  56. // src/query/defaultSerializeQueryArgs.ts
  57. import { isPlainObject } from "@reduxjs/toolkit";
  58. var cache = WeakMap ? new WeakMap() : void 0;
  59. var defaultSerializeQueryArgs = ({ endpointName, queryArgs }) => {
  60. let serialized = "";
  61. const cached = cache == null ? void 0 : cache.get(queryArgs);
  62. if (typeof cached === "string") {
  63. serialized = cached;
  64. }
  65. else {
  66. const stringified = JSON.stringify(queryArgs, (key, value) => isPlainObject(value) ? Object.keys(value).sort().reduce((acc, key2) => {
  67. acc[key2] = value[key2];
  68. return acc;
  69. }, {}) : value);
  70. if (isPlainObject(queryArgs)) {
  71. cache == null ? void 0 : cache.set(queryArgs, stringified);
  72. }
  73. serialized = stringified;
  74. }
  75. return `${endpointName}(${serialized})`;
  76. };
  77. // src/query/react/buildHooks.ts
  78. var useIsomorphicLayoutEffect = typeof window !== "undefined" && !!window.document && !!window.document.createElement ? useLayoutEffect : useEffect3;
  79. var defaultMutationStateSelector = (x) => x;
  80. var noPendingQueryStateSelector = (selected) => {
  81. if (selected.isUninitialized) {
  82. return __spreadProps(__spreadValues({}, selected), {
  83. isUninitialized: false,
  84. isFetching: true,
  85. isLoading: selected.data !== void 0 ? false : true,
  86. status: QueryStatus.pending
  87. });
  88. }
  89. return selected;
  90. };
  91. function buildHooks({ api, moduleOptions: { batch, useDispatch, useSelector, useStore, unstable__sideEffectsInRender }, serializeQueryArgs, context }) {
  92. const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : useEffect3;
  93. return { buildQueryHooks, buildMutationHook, usePrefetch };
  94. function queryStatePreSelector(currentState, lastResult, queryArgs) {
  95. if ((lastResult == null ? void 0 : lastResult.endpointName) && currentState.isUninitialized) {
  96. const { endpointName } = lastResult;
  97. const endpointDefinition = context.endpointDefinitions[endpointName];
  98. if (serializeQueryArgs({
  99. queryArgs: lastResult.originalArgs,
  100. endpointDefinition,
  101. endpointName
  102. }) === serializeQueryArgs({
  103. queryArgs,
  104. endpointDefinition,
  105. endpointName
  106. }))
  107. lastResult = void 0;
  108. }
  109. let data = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data;
  110. if (data === void 0)
  111. data = currentState.data;
  112. const hasData = data !== void 0;
  113. const isFetching = currentState.isLoading;
  114. const isLoading = !hasData && isFetching;
  115. const isSuccess = currentState.isSuccess || isFetching && hasData;
  116. return __spreadProps(__spreadValues({}, currentState), {
  117. data,
  118. currentData: currentState.data,
  119. isFetching,
  120. isLoading,
  121. isSuccess
  122. });
  123. }
  124. function usePrefetch(endpointName, defaultOptions) {
  125. const dispatch = useDispatch();
  126. const stableDefaultOptions = useShallowStableValue(defaultOptions);
  127. return useCallback((arg, options) => dispatch(api.util.prefetch(endpointName, arg, __spreadValues(__spreadValues({}, stableDefaultOptions), options))), [endpointName, dispatch, stableDefaultOptions]);
  128. }
  129. function buildQueryHooks(name) {
  130. const useQuerySubscription = (arg, { refetchOnReconnect, refetchOnFocus, refetchOnMountOrArgChange, skip = false, pollingInterval = 0 } = {}) => {
  131. const { initiate } = api.endpoints[name];
  132. const dispatch = useDispatch();
  133. const stableArg = useStableQueryArgs(skip ? skipToken : arg, defaultSerializeQueryArgs, context.endpointDefinitions[name], name);
  134. const stableSubscriptionOptions = useShallowStableValue({
  135. refetchOnReconnect,
  136. refetchOnFocus,
  137. pollingInterval
  138. });
  139. const lastRenderHadSubscription = useRef3(false);
  140. const promiseRef = useRef3();
  141. let { queryCacheKey, requestId } = promiseRef.current || {};
  142. let currentRenderHasSubscription = false;
  143. if (queryCacheKey && requestId) {
  144. const returnedValue = dispatch(api.internalActions.internal_probeSubscription({
  145. queryCacheKey,
  146. requestId
  147. }));
  148. if (true) {
  149. if (typeof returnedValue !== "boolean") {
  150. throw new Error(`Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
  151. You must add the middleware for RTK-Query to function correctly!`);
  152. }
  153. }
  154. currentRenderHasSubscription = !!returnedValue;
  155. }
  156. const subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;
  157. usePossiblyImmediateEffect(() => {
  158. lastRenderHadSubscription.current = currentRenderHasSubscription;
  159. });
  160. usePossiblyImmediateEffect(() => {
  161. if (subscriptionRemoved) {
  162. promiseRef.current = void 0;
  163. }
  164. }, [subscriptionRemoved]);
  165. usePossiblyImmediateEffect(() => {
  166. var _a;
  167. const lastPromise = promiseRef.current;
  168. if (typeof process !== "undefined" && false) {
  169. console.log(subscriptionRemoved);
  170. }
  171. if (stableArg === skipToken) {
  172. lastPromise == null ? void 0 : lastPromise.unsubscribe();
  173. promiseRef.current = void 0;
  174. return;
  175. }
  176. const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
  177. if (!lastPromise || lastPromise.arg !== stableArg) {
  178. lastPromise == null ? void 0 : lastPromise.unsubscribe();
  179. const promise = dispatch(initiate(stableArg, {
  180. subscriptionOptions: stableSubscriptionOptions,
  181. forceRefetch: refetchOnMountOrArgChange
  182. }));
  183. promiseRef.current = promise;
  184. }
  185. else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
  186. lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
  187. }
  188. }, [
  189. dispatch,
  190. initiate,
  191. refetchOnMountOrArgChange,
  192. stableArg,
  193. stableSubscriptionOptions,
  194. subscriptionRemoved
  195. ]);
  196. useEffect3(() => {
  197. return () => {
  198. var _a;
  199. (_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
  200. promiseRef.current = void 0;
  201. };
  202. }, []);
  203. return useMemo2(() => ({
  204. refetch: () => {
  205. var _a;
  206. if (!promiseRef.current)
  207. throw new Error("Cannot refetch a query that has not been started yet.");
  208. return (_a = promiseRef.current) == null ? void 0 : _a.refetch();
  209. }
  210. }), []);
  211. };
  212. const useLazyQuerySubscription = ({ refetchOnReconnect, refetchOnFocus, pollingInterval = 0 } = {}) => {
  213. const { initiate } = api.endpoints[name];
  214. const dispatch = useDispatch();
  215. const [arg, setArg] = useState(UNINITIALIZED_VALUE);
  216. const promiseRef = useRef3();
  217. const stableSubscriptionOptions = useShallowStableValue({
  218. refetchOnReconnect,
  219. refetchOnFocus,
  220. pollingInterval
  221. });
  222. usePossiblyImmediateEffect(() => {
  223. var _a, _b;
  224. const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
  225. if (stableSubscriptionOptions !== lastSubscriptionOptions) {
  226. (_b = promiseRef.current) == null ? void 0 : _b.updateSubscriptionOptions(stableSubscriptionOptions);
  227. }
  228. }, [stableSubscriptionOptions]);
  229. const subscriptionOptionsRef = useRef3(stableSubscriptionOptions);
  230. usePossiblyImmediateEffect(() => {
  231. subscriptionOptionsRef.current = stableSubscriptionOptions;
  232. }, [stableSubscriptionOptions]);
  233. const trigger = useCallback(function (arg2, preferCacheValue = false) {
  234. let promise;
  235. batch(() => {
  236. var _a;
  237. (_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
  238. promiseRef.current = promise = dispatch(initiate(arg2, {
  239. subscriptionOptions: subscriptionOptionsRef.current,
  240. forceRefetch: !preferCacheValue
  241. }));
  242. setArg(arg2);
  243. });
  244. return promise;
  245. }, [dispatch, initiate]);
  246. useEffect3(() => {
  247. return () => {
  248. var _a;
  249. (_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
  250. };
  251. }, []);
  252. useEffect3(() => {
  253. if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
  254. trigger(arg, true);
  255. }
  256. }, [arg, trigger]);
  257. return useMemo2(() => [trigger, arg], [trigger, arg]);
  258. };
  259. const useQueryState = (arg, { skip = false, selectFromResult } = {}) => {
  260. const { select } = api.endpoints[name];
  261. const stableArg = useStableQueryArgs(skip ? skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);
  262. const lastValue = useRef3();
  263. const selectDefaultResult = useMemo2(() => createSelector([
  264. select(stableArg),
  265. (_, lastResult) => lastResult,
  266. (_) => stableArg
  267. ], queryStatePreSelector), [select, stableArg]);
  268. const querySelector = useMemo2(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectDefaultResult, selectFromResult]);
  269. const currentState = useSelector((state) => querySelector(state, lastValue.current), shallowEqual2);
  270. const store = useStore();
  271. const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
  272. useIsomorphicLayoutEffect(() => {
  273. lastValue.current = newLastValue;
  274. }, [newLastValue]);
  275. return currentState;
  276. };
  277. return {
  278. useQueryState,
  279. useQuerySubscription,
  280. useLazyQuerySubscription,
  281. useLazyQuery(options) {
  282. const [trigger, arg] = useLazyQuerySubscription(options);
  283. const queryStateResults = useQueryState(arg, __spreadProps(__spreadValues({}, options), {
  284. skip: arg === UNINITIALIZED_VALUE
  285. }));
  286. const info = useMemo2(() => ({ lastArg: arg }), [arg]);
  287. return useMemo2(() => [trigger, queryStateResults, info], [trigger, queryStateResults, info]);
  288. },
  289. useQuery(arg, options) {
  290. const querySubscriptionResults = useQuerySubscription(arg, options);
  291. const queryStateResults = useQueryState(arg, __spreadValues({
  292. selectFromResult: arg === skipToken || (options == null ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector
  293. }, options));
  294. const { data, status, isLoading, isSuccess, isError, error } = queryStateResults;
  295. useDebugValue({ data, status, isLoading, isSuccess, isError, error });
  296. return useMemo2(() => __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults), [queryStateResults, querySubscriptionResults]);
  297. }
  298. };
  299. }
  300. function buildMutationHook(name) {
  301. return ({ selectFromResult = defaultMutationStateSelector, fixedCacheKey } = {}) => {
  302. const { select, initiate } = api.endpoints[name];
  303. const dispatch = useDispatch();
  304. const [promise, setPromise] = useState();
  305. useEffect3(() => () => {
  306. if (!(promise == null ? void 0 : promise.arg.fixedCacheKey)) {
  307. promise == null ? void 0 : promise.reset();
  308. }
  309. }, [promise]);
  310. const triggerMutation = useCallback(function (arg) {
  311. const promise2 = dispatch(initiate(arg, { fixedCacheKey }));
  312. setPromise(promise2);
  313. return promise2;
  314. }, [dispatch, initiate, fixedCacheKey]);
  315. const { requestId } = promise || {};
  316. const mutationSelector = useMemo2(() => createSelector([select({ fixedCacheKey, requestId: promise == null ? void 0 : promise.requestId })], selectFromResult), [select, promise, selectFromResult, fixedCacheKey]);
  317. const currentState = useSelector(mutationSelector, shallowEqual2);
  318. const originalArgs = fixedCacheKey == null ? promise == null ? void 0 : promise.arg.originalArgs : void 0;
  319. const reset = useCallback(() => {
  320. batch(() => {
  321. if (promise) {
  322. setPromise(void 0);
  323. }
  324. if (fixedCacheKey) {
  325. dispatch(api.internalActions.removeMutationResult({
  326. requestId,
  327. fixedCacheKey
  328. }));
  329. }
  330. });
  331. }, [dispatch, fixedCacheKey, promise, requestId]);
  332. const { endpointName, data, status, isLoading, isSuccess, isError, error } = currentState;
  333. useDebugValue({
  334. endpointName,
  335. data,
  336. status,
  337. isLoading,
  338. isSuccess,
  339. isError,
  340. error
  341. });
  342. const finalState = useMemo2(() => __spreadProps(__spreadValues({}, currentState), { originalArgs, reset }), [currentState, originalArgs, reset]);
  343. return useMemo2(() => [triggerMutation, finalState], [triggerMutation, finalState]);
  344. };
  345. }
  346. }
  347. // src/query/endpointDefinitions.ts
  348. var DefinitionType;
  349. (function (DefinitionType2) {
  350. DefinitionType2["query"] = "query";
  351. DefinitionType2["mutation"] = "mutation";
  352. })(DefinitionType || (DefinitionType = {}));
  353. function isQueryDefinition(e) {
  354. return e.type === DefinitionType.query;
  355. }
  356. function isMutationDefinition(e) {
  357. return e.type === DefinitionType.mutation;
  358. }
  359. // src/query/utils/capitalize.ts
  360. function capitalize(str) {
  361. return str.replace(str[0], str[0].toUpperCase());
  362. }
  363. // src/query/tsHelpers.ts
  364. function safeAssign(target, ...args) {
  365. Object.assign(target, ...args);
  366. }
  367. // src/query/react/module.ts
  368. import { useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore, batch as rrBatch } from "react-redux";
  369. var reactHooksModuleName = /* @__PURE__ */ Symbol();
  370. var reactHooksModule = ({ batch = rrBatch, useDispatch = rrUseDispatch, useSelector = rrUseSelector, useStore = rrUseStore, unstable__sideEffectsInRender = false } = {}) => ({
  371. name: reactHooksModuleName,
  372. init(api, { serializeQueryArgs }, context) {
  373. const anyApi = api;
  374. const { buildQueryHooks, buildMutationHook, usePrefetch } = buildHooks({
  375. api,
  376. moduleOptions: {
  377. batch,
  378. useDispatch,
  379. useSelector,
  380. useStore,
  381. unstable__sideEffectsInRender
  382. },
  383. serializeQueryArgs,
  384. context
  385. });
  386. safeAssign(anyApi, { usePrefetch });
  387. safeAssign(context, { batch });
  388. return {
  389. injectEndpoint(endpointName, definition) {
  390. if (isQueryDefinition(definition)) {
  391. const { useQuery, useLazyQuery, useLazyQuerySubscription, useQueryState, useQuerySubscription } = buildQueryHooks(endpointName);
  392. safeAssign(anyApi.endpoints[endpointName], {
  393. useQuery,
  394. useLazyQuery,
  395. useLazyQuerySubscription,
  396. useQueryState,
  397. useQuerySubscription
  398. });
  399. api[`use${capitalize(endpointName)}Query`] = useQuery;
  400. api[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;
  401. }
  402. else if (isMutationDefinition(definition)) {
  403. const useMutation = buildMutationHook(endpointName);
  404. safeAssign(anyApi.endpoints[endpointName], {
  405. useMutation
  406. });
  407. api[`use${capitalize(endpointName)}Mutation`] = useMutation;
  408. }
  409. }
  410. };
  411. }
  412. });
  413. // src/query/react/index.ts
  414. export * from "@reduxjs/toolkit/query";
  415. // src/query/react/ApiProvider.tsx
  416. import { configureStore } from "@reduxjs/toolkit";
  417. import { useEffect as useEffect4 } from "react";
  418. import React from "react";
  419. import { Provider } from "react-redux";
  420. import { setupListeners } from "@reduxjs/toolkit/query";
  421. function ApiProvider(props) {
  422. const [store] = React.useState(() => configureStore({
  423. reducer: {
  424. [props.api.reducerPath]: props.api.reducer
  425. },
  426. middleware: (gDM) => gDM().concat(props.api.middleware)
  427. }));
  428. useEffect4(() => props.setupListeners === false ? void 0 : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);
  429. return /* @__PURE__ */ React.createElement(Provider, {
  430. store,
  431. context: props.context
  432. }, props.children);
  433. }
  434. // src/query/react/index.ts
  435. var createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule());
  436. export { ApiProvider, createApi, reactHooksModule, reactHooksModuleName };
  437. //# sourceMappingURL=rtk-query-react.modern.development.js.map