0.2.0 - Mid migration

This commit is contained in:
Daniel Mason 2022-04-25 14:47:15 +12:00
parent 139e6a915e
commit 7e38fdbd7d
42393 changed files with 5358157 additions and 62 deletions

View file

@ -0,0 +1,34 @@
import type { Context } from 'react';
import type { ReactReduxContextValue } from 'react-redux';
import { setupListeners } from '@reduxjs/toolkit/query';
import type { Api } from '@reduxjs/toolkit/dist/query/apiTypes';
/**
* Can be used as a `Provider` if you **do not already have a Redux store**.
*
* @example
* ```tsx
* // codeblock-meta 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.
*/
export declare function ApiProvider<A extends Api<any, {}, any, any>>(props: {
children: any;
api: A;
setupListeners?: Parameters<typeof setupListeners>[1];
context?: Context<ReactReduxContextValue>;
}): JSX.Element;

View file

@ -0,0 +1,291 @@
import { useEffect } from 'react';
import { QueryStatus } from '@reduxjs/toolkit/query';
import type { QuerySubState, SubscriptionOptions, QueryKeys } from '@reduxjs/toolkit/dist/query/core/apiState';
import type { EndpointDefinitions, MutationDefinition, QueryDefinition, QueryArgFrom } from '@reduxjs/toolkit/dist/query/endpointDefinitions';
import type { MutationResultSelectorResult, SkipToken } from '@reduxjs/toolkit/dist/query/core/buildSelectors';
import type { QueryActionCreatorResult, MutationActionCreatorResult } from '@reduxjs/toolkit/dist/query/core/buildInitiate';
import type { Api } from '@reduxjs/toolkit/dist/query/apiTypes';
import type { Id, NoInfer, Override } from '@reduxjs/toolkit/dist/query/tsHelpers';
import type { CoreModule, PrefetchOptions } from '@reduxjs/toolkit/dist/query/core/module';
import type { ReactHooksModuleOptions } from './module';
import type { UninitializedValue } from './constants';
export declare const useIsomorphicLayoutEffect: typeof useEffect;
export interface QueryHooks<Definition extends QueryDefinition<any, any, any, any, any>> {
useQuery: UseQuery<Definition>;
useLazyQuery: UseLazyQuery<Definition>;
useQuerySubscription: UseQuerySubscription<Definition>;
useLazyQuerySubscription: UseLazyQuerySubscription<Definition>;
useQueryState: UseQueryState<Definition>;
}
export interface 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
*/
export declare 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>) => UseQueryStateResult<D, R> & ReturnType<UseQuerySubscription<D>>;
interface UseQuerySubscriptionOptions extends 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 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
* ```tsx
* // 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;
/**
* 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
*/
export declare type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions) => Pick<QueryActionCreatorResult<D>, 'refetch'>;
export declare 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
*
*/
export declare type UseLazyQuery<D extends QueryDefinition<any, any, any, any>> = <R = UseQueryStateDefaultResult<D>>(options?: SubscriptionOptions & Omit<UseQueryStateOptions<D, R>, 'skip'>) => [
(arg: QueryArgFrom<D>) => void,
UseQueryStateResult<D, R>,
UseLazyQueryLastPromiseInfo<D>
];
/**
* 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
*/
export declare type UseLazyQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (options?: SubscriptionOptions) => [(arg: QueryArgFrom<D>) => void, QueryArgFrom<D> | UninitializedValue];
export declare 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
*/
export declare type UseQueryState<D extends QueryDefinition<any, any, any, any>> = <R = UseQueryStateDefaultResult<D>>(arg: QueryArgFrom<D> | SkipToken, options?: UseQueryStateOptions<D, R>) => UseQueryStateResult<D, R>;
export declare 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>;
};
export declare type UseQueryStateResult<_ extends QueryDefinition<any, any, any, any>, R> = NoInfer<R>;
declare type UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> = QuerySubState<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;
};
declare type UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> = Id<Override<Extract<UseQueryStateBaseResult<D>, {
status: QueryStatus.uninitialized;
}>, {
isUninitialized: true;
}> | Override<UseQueryStateBaseResult<D>, {
isLoading: true;
isFetching: boolean;
data: undefined;
} | ({
isSuccess: true;
isFetching: boolean;
error: undefined;
} & Required<Pick<UseQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp'>>) | ({
isError: true;
} & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>)>> & {
/**
* @deprecated will be removed in the next version
* please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
* and `isUninitialized` flags instead
*/
status: QueryStatus;
};
export declare type MutationStateSelector<R extends Record<string, any>, D extends MutationDefinition<any, any, any, any>> = (state: MutationResultSelectorResult<D>) => R;
export declare type UseMutationStateOptions<D extends MutationDefinition<any, any, any, any>, R extends Record<string, any>> = {
selectFromResult?: MutationStateSelector<R, D>;
};
export declare type UseMutationStateResult<D extends MutationDefinition<any, any, any, any>, R> = NoInfer<R> & {
originalArgs?: QueryArgFrom<D>;
};
/**
* 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
*/
export declare type UseMutation<D extends MutationDefinition<any, any, any, any>> = <R extends Record<string, any> = MutationResultSelectorResult<D>>(options?: UseMutationStateOptions<D, R>) => [
(arg: QueryArgFrom<D>) => MutationActionCreatorResult<D>,
UseMutationStateResult<D, R>
];
/**
*
* @param opts.api - An API with defined endpoints to create hooks for
* @param opts.moduleOptions.batch - The version of the `batchedUpdates` function to be used
* @param opts.moduleOptions.useDispatch - The version of the `useDispatch` hook to be used
* @param opts.moduleOptions.useSelector - The version of the `useSelector` hook to be used
* @returns An object containing functions to generate hooks based on an endpoint
*/
export declare function buildHooks<Definitions extends EndpointDefinitions>({ api, moduleOptions: { batch, useDispatch, useSelector, useStore }, }: {
api: Api<any, Definitions, any, any, CoreModule>;
moduleOptions: Required<ReactHooksModuleOptions>;
}): {
buildQueryHooks: (name: string) => QueryHooks<any>;
buildMutationHook: (name: string) => UseMutation<any>;
usePrefetch: <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, defaultOptions?: PrefetchOptions | undefined) => (arg: any, options?: PrefetchOptions | undefined) => void;
};
export {};

View file

@ -0,0 +1,2 @@
export declare const UNINITIALIZED_VALUE: unique symbol;
export declare type UninitializedValue = typeof UNINITIALIZED_VALUE;

View file

@ -0,0 +1,6 @@
import { CreateApi } from '@reduxjs/toolkit/query';
import { reactHooksModule, reactHooksModuleName } from './module';
export * from '@reduxjs/toolkit/query';
export { ApiProvider } from './ApiProvider';
declare const createApi: CreateApi<typeof import("@reduxjs/toolkit/dist/query/core/module").coreModuleName | typeof reactHooksModuleName>;
export { createApi, reactHooksModule };

View file

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

View file

@ -0,0 +1,60 @@
import type { MutationHooks, QueryHooks } from './buildHooks';
import type { EndpointDefinitions, QueryDefinition, MutationDefinition, QueryArgFrom } from '@reduxjs/toolkit/dist/query/endpointDefinitions';
import type { Module } from '../apiTypes';
import type { BaseQueryFn } from '@reduxjs/toolkit/dist/query/baseQueryTypes';
import type { HooksWithUniqueNames } from './versionedTypes';
import type { QueryKeys } from '../core/apiState';
import type { PrefetchOptions } from '../core/module';
export declare const reactHooksModuleName: unique symbol;
export declare type ReactHooksModule = typeof reactHooksModuleName;
declare module '@reduxjs/toolkit/dist/query/apiTypes' {
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>;
}
}
declare type RR = typeof import('react-redux');
export interface ReactHooksModuleOptions {
/**
* The version of the `batchedUpdates` function to be used
*/
batch?: RR['batch'];
/**
* 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'];
}
/**
* Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.
*
* @example
* ```ts
* const MyContext = React.createContext<ReactReduxContextValue>(null as any);
* const customCreateApi = buildCreateApi(
* coreModule(),
* reactHooksModule({ useDispatch: createDispatchHook(MyContext) })
* );
* ```
*
* @returns A module for use with `buildCreateApi`
*/
export declare const reactHooksModule: ({ batch, useDispatch, useSelector, useStore, }?: ReactHooksModuleOptions) => Module<ReactHooksModule>;
export {};

View file

@ -0,0 +1,376 @@
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = function (obj, key, value) { return key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value; };
var __spreadValues = function (a, b) {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var _i = 0, _c = __getOwnPropSymbols(b); _i < _c.length; _i++) {
var prop = _c[_i];
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = function (a, b) { return __defProps(a, __getOwnPropDescs(b)); };
var __markAsModule = function (target) { return __defProp(target, "__esModule", { value: true }); };
var __export = function (target, all) {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __reExport = function (target, module2, desc) {
if (module2 && typeof module2 === "object" || typeof module2 === "function") {
var _loop_1 = function (key) {
if (!__hasOwnProp.call(target, key) && key !== "default")
__defProp(target, key, { get: function () { return module2[key]; }, enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
};
for (var _i = 0, _c = __getOwnPropNames(module2); _i < _c.length; _i++) {
var key = _c[_i];
_loop_1(key);
}
}
return target;
};
var __toModule = function (module2) {
return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: function () { return module2.default; }, enumerable: true } : { value: module2, enumerable: true })), module2);
};
// src/query/react/index.ts
__markAsModule(exports);
__export(exports, {
ApiProvider: function () { return ApiProvider; },
createApi: function () { return createApi; },
reactHooksModule: function () { return reactHooksModule; }
});
var import_query3 = __toModule(require("@reduxjs/toolkit/query"));
// src/query/react/buildHooks.ts
var import_toolkit = __toModule(require("@reduxjs/toolkit"));
var import_react2 = __toModule(require("react"));
var import_query = __toModule(require("@reduxjs/toolkit/query"));
var import_react_redux2 = __toModule(require("react-redux"));
// src/query/react/useShallowStableValue.ts
var import_react = __toModule(require("react"));
var import_react_redux = __toModule(require("react-redux"));
function useShallowStableValue(value) {
var cache = (0, import_react.useRef)(value);
(0, import_react.useEffect)(function () {
if (!(0, import_react_redux.shallowEqual)(cache.current, value)) {
cache.current = value;
}
}, [value]);
return (0, import_react_redux.shallowEqual)(cache.current, value) ? cache.current : value;
}
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/buildHooks.ts
var useIsomorphicLayoutEffect = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined" ? import_react2.useLayoutEffect : import_react2.useEffect;
var defaultQueryStateSelector = function (x) { return x; };
var defaultMutationStateSelector = function (x) { return x; };
var queryStatePreSelector = function (currentState, lastResult) {
var _a;
var data = (_a = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data) != null ? _a : currentState.data;
var isFetching = currentState.isLoading;
var isLoading = !data && isFetching;
var isSuccess = currentState.isSuccess || isFetching && !!data;
return __spreadProps(__spreadValues({}, currentState), {
data: data,
isFetching: isFetching,
isLoading: isLoading,
isSuccess: isSuccess
});
};
var noPendingQueryStateSelector = function (selected) {
if (selected.isUninitialized) {
return __spreadProps(__spreadValues({}, selected), {
isUninitialized: false,
isFetching: true,
isLoading: true,
status: import_query.QueryStatus.pending
});
}
return selected;
};
function buildHooks(_c) {
var api = _c.api, _d = _c.moduleOptions, batch = _d.batch, useDispatch = _d.useDispatch, useSelector = _d.useSelector, useStore = _d.useStore;
return { buildQueryHooks: buildQueryHooks, buildMutationHook: buildMutationHook, usePrefetch: usePrefetch };
function usePrefetch(endpointName, defaultOptions) {
var dispatch = useDispatch();
var stableDefaultOptions = useShallowStableValue(defaultOptions);
return (0, import_react2.useCallback)(function (arg, options) { return dispatch(api.util.prefetch(endpointName, arg, __spreadValues(__spreadValues({}, stableDefaultOptions), options))); }, [endpointName, dispatch, stableDefaultOptions]);
}
function buildQueryHooks(name) {
var useQuerySubscription = function (arg, _c) {
var _d = _c === void 0 ? {} : _c, refetchOnReconnect = _d.refetchOnReconnect, refetchOnFocus = _d.refetchOnFocus, refetchOnMountOrArgChange = _d.refetchOnMountOrArgChange, _e = _d.skip, skip = _e === void 0 ? false : _e, _f = _d.pollingInterval, pollingInterval = _f === void 0 ? 0 : _f;
var initiate = api.endpoints[name].initiate;
var dispatch = useDispatch();
var stableArg = useShallowStableValue(skip ? import_query.skipToken : arg);
var stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect: refetchOnReconnect,
refetchOnFocus: refetchOnFocus,
pollingInterval: pollingInterval
});
var promiseRef = (0, import_react2.useRef)();
(0, import_react2.useEffect)(function () {
var _a;
var lastPromise = promiseRef.current;
if (stableArg === import_query.skipToken) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
promiseRef.current = void 0;
return;
}
var lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (!lastPromise || lastPromise.arg !== stableArg) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
var promise = dispatch(initiate(stableArg, {
subscriptionOptions: stableSubscriptionOptions,
forceRefetch: refetchOnMountOrArgChange
}));
promiseRef.current = promise;
}
else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [
dispatch,
initiate,
refetchOnMountOrArgChange,
stableArg,
stableSubscriptionOptions
]);
(0, import_react2.useEffect)(function () {
return function () {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return (0, import_react2.useMemo)(function () { return ({
refetch: function () {
var _a;
return void ((_a = promiseRef.current) == null ? void 0 : _a.refetch());
}
}); }, []);
};
var useLazyQuerySubscription = function (_c) {
var _d = _c === void 0 ? {} : _c, refetchOnReconnect = _d.refetchOnReconnect, refetchOnFocus = _d.refetchOnFocus, _e = _d.pollingInterval, pollingInterval = _e === void 0 ? 0 : _e;
var initiate = api.endpoints[name].initiate;
var dispatch = useDispatch();
var _f = (0, import_react2.useState)(UNINITIALIZED_VALUE), arg = _f[0], setArg = _f[1];
var promiseRef = (0, import_react2.useRef)();
var stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect: refetchOnReconnect,
refetchOnFocus: refetchOnFocus,
pollingInterval: pollingInterval
});
(0, import_react2.useEffect)(function () {
var _a, _b;
var lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (stableSubscriptionOptions !== lastSubscriptionOptions) {
(_b = promiseRef.current) == null ? void 0 : _b.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [stableSubscriptionOptions]);
var subscriptionOptionsRef = (0, import_react2.useRef)(stableSubscriptionOptions);
(0, import_react2.useEffect)(function () {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
var trigger = (0, import_react2.useCallback)(function (arg2, preferCacheValue) {
if (preferCacheValue === void 0) { preferCacheValue = false; }
batch(function () {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
}, [dispatch, initiate]);
(0, import_react2.useEffect)(function () {
return function () {
var _a;
(_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
};
}, []);
(0, import_react2.useEffect)(function () {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return (0, import_react2.useMemo)(function () { return [trigger, arg]; }, [trigger, arg]);
};
var useQueryState = function (arg, _c) {
var _d = _c === void 0 ? {} : _c, _e = _d.skip, skip = _e === void 0 ? false : _e, _f = _d.selectFromResult, selectFromResult = _f === void 0 ? defaultQueryStateSelector : _f;
var select = api.endpoints[name].select;
var stableArg = useShallowStableValue(skip ? import_query.skipToken : arg);
var lastValue = (0, import_react2.useRef)();
var selectDefaultResult = (0, import_react2.useMemo)(function () { return (0, import_toolkit.createSelector)([select(stableArg), function (_, lastResult) { return lastResult; }], queryStatePreSelector); }, [select, stableArg]);
var querySelector = (0, import_react2.useMemo)(function () { return (0, import_toolkit.createSelector)([selectDefaultResult], selectFromResult); }, [selectDefaultResult, selectFromResult]);
var currentState = useSelector(function (state) { return querySelector(state, lastValue.current); }, import_react_redux2.shallowEqual);
var store = useStore();
var newLastValue = selectDefaultResult(store.getState(), lastValue.current);
useIsomorphicLayoutEffect(function () {
lastValue.current = newLastValue;
}, [newLastValue]);
return currentState;
};
return {
useQueryState: useQueryState,
useQuerySubscription: useQuerySubscription,
useLazyQuerySubscription: useLazyQuerySubscription,
useLazyQuery: function (options) {
var _c = useLazyQuerySubscription(options), trigger = _c[0], arg = _c[1];
var queryStateResults = useQueryState(arg, __spreadProps(__spreadValues({}, options), {
skip: arg === UNINITIALIZED_VALUE
}));
var info = (0, import_react2.useMemo)(function () { return ({ lastArg: arg }); }, [arg]);
return (0, import_react2.useMemo)(function () { return [trigger, queryStateResults, info]; }, [trigger, queryStateResults, info]);
},
useQuery: function (arg, options) {
var querySubscriptionResults = useQuerySubscription(arg, options);
var queryStateResults = useQueryState(arg, __spreadValues({
selectFromResult: arg === import_query.skipToken || (options == null ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector
}, options));
return (0, import_react2.useMemo)(function () { return __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults); }, [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return function (_c) {
var _d = _c === void 0 ? {} : _c, _e = _d.selectFromResult, selectFromResult = _e === void 0 ? defaultMutationStateSelector : _e;
var _a;
var _f = api.endpoints[name], select = _f.select, initiate = _f.initiate;
var dispatch = useDispatch();
var _g = (0, import_react2.useState)(), requestId = _g[0], setRequestId = _g[1];
var promiseRef = (0, import_react2.useRef)();
(0, import_react2.useEffect)(function () {
return function () {
var _a2;
(_a2 = promiseRef.current) == null ? void 0 : _a2.unsubscribe();
promiseRef.current = void 0;
};
}, []);
var triggerMutation = (0, import_react2.useCallback)(function (arg) {
var promise;
batch(function () {
var _a2;
(_a2 = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a2.unsubscribe();
promise = dispatch(initiate(arg));
promiseRef.current = promise;
setRequestId(promise.requestId);
});
return promise;
}, [dispatch, initiate]);
var mutationSelector = (0, import_react2.useMemo)(function () { return (0, import_toolkit.createSelector)([select(requestId || import_query.skipToken)], function (subState) { return selectFromResult(subState); }); }, [select, requestId, selectFromResult]);
var currentState = useSelector(mutationSelector, import_react_redux2.shallowEqual);
var originalArgs = (_a = promiseRef.current) == null ? void 0 : _a.arg.originalArgs;
var finalState = (0, import_react2.useMemo)(function () { return __spreadProps(__spreadValues({}, currentState), {
originalArgs: originalArgs
}); }, [currentState, originalArgs]);
return (0, import_react2.useMemo)(function () { return [triggerMutation, finalState]; }, [triggerMutation, finalState]);
};
}
}
// src/query/endpointDefinitions.ts
var DefinitionType;
(function (DefinitionType2) {
DefinitionType2["query"] = "query";
DefinitionType2["mutation"] = "mutation";
})(DefinitionType || (DefinitionType = {}));
function isQueryDefinition(e) {
return e.type === DefinitionType.query;
}
function isMutationDefinition(e) {
return e.type === DefinitionType.mutation;
}
// src/query/utils/capitalize.ts
function capitalize(str) {
return str.replace(str[0], str[0].toUpperCase());
}
// src/query/tsHelpers.ts
function safeAssign(target) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
Object.assign.apply(Object, __spreadArray([target], args));
}
// src/query/react/module.ts
var import_react_redux3 = __toModule(require("react-redux"));
var reactHooksModuleName = /* @__PURE__ */ Symbol();
var reactHooksModule = function (_c) {
var _d = _c === void 0 ? {} : _c, _e = _d.batch, batch = _e === void 0 ? import_react_redux3.batch : _e, _f = _d.useDispatch, useDispatch = _f === void 0 ? import_react_redux3.useDispatch : _f, _g = _d.useSelector, useSelector = _g === void 0 ? import_react_redux3.useSelector : _g, _h = _d.useStore, useStore = _h === void 0 ? import_react_redux3.useStore : _h;
return ({
name: reactHooksModuleName,
init: function (api, options, context) {
var anyApi = api;
var _c = buildHooks({
api: api,
moduleOptions: { batch: batch, useDispatch: useDispatch, useSelector: useSelector, useStore: useStore }
}), buildQueryHooks = _c.buildQueryHooks, buildMutationHook = _c.buildMutationHook, usePrefetch = _c.usePrefetch;
safeAssign(anyApi, { usePrefetch: usePrefetch });
safeAssign(context, { batch: batch });
return {
injectEndpoint: function (endpointName, definition) {
if (isQueryDefinition(definition)) {
var _c = buildQueryHooks(endpointName), useQuery = _c.useQuery, useLazyQuery = _c.useLazyQuery, useLazyQuerySubscription = _c.useLazyQuerySubscription, useQueryState = _c.useQueryState, useQuerySubscription = _c.useQuerySubscription;
safeAssign(anyApi.endpoints[endpointName], {
useQuery: useQuery,
useLazyQuery: useLazyQuery,
useLazyQuerySubscription: useLazyQuerySubscription,
useQueryState: useQueryState,
useQuerySubscription: useQuerySubscription
});
api["use" + capitalize(endpointName) + "Query"] = useQuery;
api["useLazy" + capitalize(endpointName) + "Query"] = useLazyQuery;
}
else if (isMutationDefinition(definition)) {
var useMutation = buildMutationHook(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useMutation: useMutation
});
api["use" + capitalize(endpointName) + "Mutation"] = useMutation;
}
}
};
}
});
};
// src/query/react/index.ts
__reExport(exports, __toModule(require("@reduxjs/toolkit/query")));
// src/query/react/ApiProvider.tsx
var import_toolkit2 = __toModule(require("@reduxjs/toolkit"));
var import_react3 = __toModule(require("react"));
var import_react_redux4 = __toModule(require("react-redux"));
var import_query2 = __toModule(require("@reduxjs/toolkit/query"));
function ApiProvider(props) {
var store = import_react3.default.useState(function () {
var _c;
return (0, import_toolkit2.configureStore)({
reducer: (_c = {},
_c[props.api.reducerPath] = props.api.reducer,
_c),
middleware: function (gDM) { return gDM().concat(props.api.middleware); }
});
})[0];
(0, import_query2.setupListeners)(store.dispatch, props.setupListeners);
return /* @__PURE__ */ import_react3.default.createElement(import_react_redux4.Provider, {
store: store,
context: props.context
}, props.children);
}
// src/query/react/index.ts
var createApi = /* @__PURE__ */ (0, import_query3.buildCreateApi)((0, import_query3.coreModule)(), reactHooksModule());
//# sourceMappingURL=module.js.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,346 @@
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
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 = function (obj, key, value) { return key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value; };
var __spreadValues = function (a, b) {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var _i = 0, _c = __getOwnPropSymbols(b); _i < _c.length; _i++) {
var prop = _c[_i];
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = function (a, b) { return __defProps(a, __getOwnPropDescs(b)); };
// src/query/react/index.ts
import { coreModule, buildCreateApi } from "@reduxjs/toolkit/query";
// src/query/react/buildHooks.ts
import { createSelector } from "@reduxjs/toolkit";
import { useCallback, useEffect as useEffect2, useLayoutEffect, useMemo, useRef as useRef2, useState } from "react";
import { QueryStatus, skipToken } from "@reduxjs/toolkit/query";
import { shallowEqual as shallowEqual2 } from "react-redux";
// src/query/react/useShallowStableValue.ts
import { useEffect, useRef } from "react";
import { shallowEqual } from "react-redux";
function useShallowStableValue(value) {
var cache = useRef(value);
useEffect(function () {
if (!shallowEqual(cache.current, value)) {
cache.current = value;
}
}, [value]);
return shallowEqual(cache.current, value) ? cache.current : value;
}
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/buildHooks.ts
var useIsomorphicLayoutEffect = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined" ? useLayoutEffect : useEffect2;
var defaultQueryStateSelector = function (x) { return x; };
var defaultMutationStateSelector = function (x) { return x; };
var queryStatePreSelector = function (currentState, lastResult) {
var _a;
var data = (_a = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data) != null ? _a : currentState.data;
var isFetching = currentState.isLoading;
var isLoading = !data && isFetching;
var isSuccess = currentState.isSuccess || isFetching && !!data;
return __spreadProps(__spreadValues({}, currentState), {
data: data,
isFetching: isFetching,
isLoading: isLoading,
isSuccess: isSuccess
});
};
var noPendingQueryStateSelector = function (selected) {
if (selected.isUninitialized) {
return __spreadProps(__spreadValues({}, selected), {
isUninitialized: false,
isFetching: true,
isLoading: true,
status: QueryStatus.pending
});
}
return selected;
};
function buildHooks(_c) {
var api = _c.api, _d = _c.moduleOptions, batch = _d.batch, useDispatch = _d.useDispatch, useSelector = _d.useSelector, useStore = _d.useStore;
return { buildQueryHooks: buildQueryHooks, buildMutationHook: buildMutationHook, usePrefetch: usePrefetch };
function usePrefetch(endpointName, defaultOptions) {
var dispatch = useDispatch();
var stableDefaultOptions = useShallowStableValue(defaultOptions);
return useCallback(function (arg, options) { return dispatch(api.util.prefetch(endpointName, arg, __spreadValues(__spreadValues({}, stableDefaultOptions), options))); }, [endpointName, dispatch, stableDefaultOptions]);
}
function buildQueryHooks(name) {
var useQuerySubscription = function (arg, _c) {
var _d = _c === void 0 ? {} : _c, refetchOnReconnect = _d.refetchOnReconnect, refetchOnFocus = _d.refetchOnFocus, refetchOnMountOrArgChange = _d.refetchOnMountOrArgChange, _e = _d.skip, skip = _e === void 0 ? false : _e, _f = _d.pollingInterval, pollingInterval = _f === void 0 ? 0 : _f;
var initiate = api.endpoints[name].initiate;
var dispatch = useDispatch();
var stableArg = useShallowStableValue(skip ? skipToken : arg);
var stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect: refetchOnReconnect,
refetchOnFocus: refetchOnFocus,
pollingInterval: pollingInterval
});
var promiseRef = useRef2();
useEffect2(function () {
var _a;
var lastPromise = promiseRef.current;
if (stableArg === skipToken) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
promiseRef.current = void 0;
return;
}
var lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (!lastPromise || lastPromise.arg !== stableArg) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
var promise = dispatch(initiate(stableArg, {
subscriptionOptions: stableSubscriptionOptions,
forceRefetch: refetchOnMountOrArgChange
}));
promiseRef.current = promise;
}
else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [
dispatch,
initiate,
refetchOnMountOrArgChange,
stableArg,
stableSubscriptionOptions
]);
useEffect2(function () {
return function () {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return useMemo(function () { return ({
refetch: function () {
var _a;
return void ((_a = promiseRef.current) == null ? void 0 : _a.refetch());
}
}); }, []);
};
var useLazyQuerySubscription = function (_c) {
var _d = _c === void 0 ? {} : _c, refetchOnReconnect = _d.refetchOnReconnect, refetchOnFocus = _d.refetchOnFocus, _e = _d.pollingInterval, pollingInterval = _e === void 0 ? 0 : _e;
var initiate = api.endpoints[name].initiate;
var dispatch = useDispatch();
var _f = useState(UNINITIALIZED_VALUE), arg = _f[0], setArg = _f[1];
var promiseRef = useRef2();
var stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect: refetchOnReconnect,
refetchOnFocus: refetchOnFocus,
pollingInterval: pollingInterval
});
useEffect2(function () {
var _a, _b;
var lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (stableSubscriptionOptions !== lastSubscriptionOptions) {
(_b = promiseRef.current) == null ? void 0 : _b.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [stableSubscriptionOptions]);
var subscriptionOptionsRef = useRef2(stableSubscriptionOptions);
useEffect2(function () {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
var trigger = useCallback(function (arg2, preferCacheValue) {
if (preferCacheValue === void 0) { preferCacheValue = false; }
batch(function () {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
}, [dispatch, initiate]);
useEffect2(function () {
return function () {
var _a;
(_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
};
}, []);
useEffect2(function () {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return useMemo(function () { return [trigger, arg]; }, [trigger, arg]);
};
var useQueryState = function (arg, _c) {
var _d = _c === void 0 ? {} : _c, _e = _d.skip, skip = _e === void 0 ? false : _e, _f = _d.selectFromResult, selectFromResult = _f === void 0 ? defaultQueryStateSelector : _f;
var select = api.endpoints[name].select;
var stableArg = useShallowStableValue(skip ? skipToken : arg);
var lastValue = useRef2();
var selectDefaultResult = useMemo(function () { return createSelector([select(stableArg), function (_, lastResult) { return lastResult; }], queryStatePreSelector); }, [select, stableArg]);
var querySelector = useMemo(function () { return createSelector([selectDefaultResult], selectFromResult); }, [selectDefaultResult, selectFromResult]);
var currentState = useSelector(function (state) { return querySelector(state, lastValue.current); }, shallowEqual2);
var store = useStore();
var newLastValue = selectDefaultResult(store.getState(), lastValue.current);
useIsomorphicLayoutEffect(function () {
lastValue.current = newLastValue;
}, [newLastValue]);
return currentState;
};
return {
useQueryState: useQueryState,
useQuerySubscription: useQuerySubscription,
useLazyQuerySubscription: useLazyQuerySubscription,
useLazyQuery: function (options) {
var _c = useLazyQuerySubscription(options), trigger = _c[0], arg = _c[1];
var queryStateResults = useQueryState(arg, __spreadProps(__spreadValues({}, options), {
skip: arg === UNINITIALIZED_VALUE
}));
var info = useMemo(function () { return ({ lastArg: arg }); }, [arg]);
return useMemo(function () { return [trigger, queryStateResults, info]; }, [trigger, queryStateResults, info]);
},
useQuery: function (arg, options) {
var querySubscriptionResults = useQuerySubscription(arg, options);
var queryStateResults = useQueryState(arg, __spreadValues({
selectFromResult: arg === skipToken || (options == null ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector
}, options));
return useMemo(function () { return __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults); }, [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return function (_c) {
var _d = _c === void 0 ? {} : _c, _e = _d.selectFromResult, selectFromResult = _e === void 0 ? defaultMutationStateSelector : _e;
var _a;
var _f = api.endpoints[name], select = _f.select, initiate = _f.initiate;
var dispatch = useDispatch();
var _g = useState(), requestId = _g[0], setRequestId = _g[1];
var promiseRef = useRef2();
useEffect2(function () {
return function () {
var _a2;
(_a2 = promiseRef.current) == null ? void 0 : _a2.unsubscribe();
promiseRef.current = void 0;
};
}, []);
var triggerMutation = useCallback(function (arg) {
var promise;
batch(function () {
var _a2;
(_a2 = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a2.unsubscribe();
promise = dispatch(initiate(arg));
promiseRef.current = promise;
setRequestId(promise.requestId);
});
return promise;
}, [dispatch, initiate]);
var mutationSelector = useMemo(function () { return createSelector([select(requestId || skipToken)], function (subState) { return selectFromResult(subState); }); }, [select, requestId, selectFromResult]);
var currentState = useSelector(mutationSelector, shallowEqual2);
var originalArgs = (_a = promiseRef.current) == null ? void 0 : _a.arg.originalArgs;
var finalState = useMemo(function () { return __spreadProps(__spreadValues({}, currentState), {
originalArgs: originalArgs
}); }, [currentState, originalArgs]);
return useMemo(function () { return [triggerMutation, finalState]; }, [triggerMutation, finalState]);
};
}
}
// src/query/endpointDefinitions.ts
var DefinitionType;
(function (DefinitionType2) {
DefinitionType2["query"] = "query";
DefinitionType2["mutation"] = "mutation";
})(DefinitionType || (DefinitionType = {}));
function isQueryDefinition(e) {
return e.type === DefinitionType.query;
}
function isMutationDefinition(e) {
return e.type === DefinitionType.mutation;
}
// src/query/utils/capitalize.ts
function capitalize(str) {
return str.replace(str[0], str[0].toUpperCase());
}
// src/query/tsHelpers.ts
function safeAssign(target) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
Object.assign.apply(Object, __spreadArray([target], args));
}
// src/query/react/module.ts
import { useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore, batch as rrBatch } from "react-redux";
var reactHooksModuleName = /* @__PURE__ */ Symbol();
var reactHooksModule = function (_c) {
var _d = _c === void 0 ? {} : _c, _e = _d.batch, batch = _e === void 0 ? rrBatch : _e, _f = _d.useDispatch, useDispatch = _f === void 0 ? rrUseDispatch : _f, _g = _d.useSelector, useSelector = _g === void 0 ? rrUseSelector : _g, _h = _d.useStore, useStore = _h === void 0 ? rrUseStore : _h;
return ({
name: reactHooksModuleName,
init: function (api, options, context) {
var anyApi = api;
var _c = buildHooks({
api: api,
moduleOptions: { batch: batch, useDispatch: useDispatch, useSelector: useSelector, useStore: useStore }
}), buildQueryHooks = _c.buildQueryHooks, buildMutationHook = _c.buildMutationHook, usePrefetch = _c.usePrefetch;
safeAssign(anyApi, { usePrefetch: usePrefetch });
safeAssign(context, { batch: batch });
return {
injectEndpoint: function (endpointName, definition) {
if (isQueryDefinition(definition)) {
var _c = buildQueryHooks(endpointName), useQuery = _c.useQuery, useLazyQuery = _c.useLazyQuery, useLazyQuerySubscription = _c.useLazyQuerySubscription, useQueryState = _c.useQueryState, useQuerySubscription = _c.useQuerySubscription;
safeAssign(anyApi.endpoints[endpointName], {
useQuery: useQuery,
useLazyQuery: useLazyQuery,
useLazyQuerySubscription: useLazyQuerySubscription,
useQueryState: useQueryState,
useQuerySubscription: useQuerySubscription
});
api["use" + capitalize(endpointName) + "Query"] = useQuery;
api["useLazy" + capitalize(endpointName) + "Query"] = useLazyQuery;
}
else if (isMutationDefinition(definition)) {
var useMutation = buildMutationHook(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useMutation: useMutation
});
api["use" + capitalize(endpointName) + "Mutation"] = useMutation;
}
}
};
}
});
};
// src/query/react/index.ts
export * from "@reduxjs/toolkit/query";
// src/query/react/ApiProvider.tsx
import { configureStore } from "@reduxjs/toolkit";
import React from "react";
import { Provider } from "react-redux";
import { setupListeners } from "@reduxjs/toolkit/query";
function ApiProvider(props) {
var store = React.useState(function () {
var _c;
return configureStore({
reducer: (_c = {},
_c[props.api.reducerPath] = props.api.reducer,
_c),
middleware: function (gDM) { return gDM().concat(props.api.middleware); }
});
})[0];
setupListeners(store.dispatch, props.setupListeners);
return /* @__PURE__ */ React.createElement(Provider, {
store: store,
context: props.context
}, props.children);
}
// src/query/react/index.ts
var createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule());
export { ApiProvider, createApi, reactHooksModule };
//# sourceMappingURL=module.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,324 @@
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));
// src/query/react/index.ts
import { coreModule, buildCreateApi } from "@reduxjs/toolkit/query";
// src/query/react/buildHooks.ts
import { createSelector } from "@reduxjs/toolkit";
import { useCallback, useEffect as useEffect2, useLayoutEffect, useMemo, useRef as useRef2, useState } from "react";
import { QueryStatus, skipToken } from "@reduxjs/toolkit/query";
import { shallowEqual as shallowEqual2 } from "react-redux";
// src/query/react/useShallowStableValue.ts
import { useEffect, useRef } from "react";
import { shallowEqual } from "react-redux";
function useShallowStableValue(value) {
const cache = useRef(value);
useEffect(() => {
if (!shallowEqual(cache.current, value)) {
cache.current = value;
}
}, [value]);
return shallowEqual(cache.current, value) ? cache.current : value;
}
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/buildHooks.ts
var useIsomorphicLayoutEffect = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined" ? useLayoutEffect : useEffect2;
var defaultQueryStateSelector = (x) => x;
var defaultMutationStateSelector = (x) => x;
var queryStatePreSelector = (currentState, lastResult) => {
var _a;
const data = (_a = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data) != null ? _a : currentState.data;
const isFetching = currentState.isLoading;
const isLoading = !data && isFetching;
const isSuccess = currentState.isSuccess || isFetching && !!data;
return __spreadProps(__spreadValues({}, currentState), {
data,
isFetching,
isLoading,
isSuccess
});
};
var noPendingQueryStateSelector = (selected) => {
if (selected.isUninitialized) {
return __spreadProps(__spreadValues({}, selected), {
isUninitialized: false,
isFetching: true,
isLoading: true,
status: QueryStatus.pending
});
}
return selected;
};
function buildHooks({ api, moduleOptions: { batch, useDispatch, useSelector, useStore } }) {
return { buildQueryHooks, buildMutationHook, usePrefetch };
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 } = {}) => {
const { initiate } = api.endpoints[name];
const dispatch = useDispatch();
const stableArg = useShallowStableValue(skip ? skipToken : arg);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval
});
const promiseRef = useRef2();
useEffect2(() => {
var _a;
const lastPromise = promiseRef.current;
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
]);
useEffect2(() => {
return () => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return useMemo(() => ({
refetch: () => {
var _a;
return void ((_a = promiseRef.current) == null ? void 0 : _a.refetch());
}
}), []);
};
const useLazyQuerySubscription = ({ refetchOnReconnect, refetchOnFocus, pollingInterval = 0 } = {}) => {
const { initiate } = api.endpoints[name];
const dispatch = useDispatch();
const [arg, setArg] = useState(UNINITIALIZED_VALUE);
const promiseRef = useRef2();
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval
});
useEffect2(() => {
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 = useRef2(stableSubscriptionOptions);
useEffect2(() => {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
const trigger = useCallback(function (arg2, preferCacheValue = false) {
batch(() => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
}, [dispatch, initiate]);
useEffect2(() => {
return () => {
var _a;
(_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
};
}, []);
useEffect2(() => {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return useMemo(() => [trigger, arg], [trigger, arg]);
};
const useQueryState = (arg, { skip = false, selectFromResult = defaultQueryStateSelector } = {}) => {
const { select } = api.endpoints[name];
const stableArg = useShallowStableValue(skip ? skipToken : arg);
const lastValue = useRef2();
const selectDefaultResult = useMemo(() => createSelector([select(stableArg), (_, lastResult) => lastResult], queryStatePreSelector), [select, stableArg]);
const querySelector = useMemo(() => createSelector([selectDefaultResult], selectFromResult), [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 = useMemo(() => ({ lastArg: arg }), [arg]);
return useMemo(() => [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));
return useMemo(() => __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults), [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return ({ selectFromResult = defaultMutationStateSelector } = {}) => {
var _a;
const { select, initiate } = api.endpoints[name];
const dispatch = useDispatch();
const [requestId, setRequestId] = useState();
const promiseRef = useRef2();
useEffect2(() => {
return () => {
var _a2;
(_a2 = promiseRef.current) == null ? void 0 : _a2.unsubscribe();
promiseRef.current = void 0;
};
}, []);
const triggerMutation = useCallback(function (arg) {
let promise;
batch(() => {
var _a2;
(_a2 = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a2.unsubscribe();
promise = dispatch(initiate(arg));
promiseRef.current = promise;
setRequestId(promise.requestId);
});
return promise;
}, [dispatch, initiate]);
const mutationSelector = useMemo(() => createSelector([select(requestId || skipToken)], (subState) => selectFromResult(subState)), [select, requestId, selectFromResult]);
const currentState = useSelector(mutationSelector, shallowEqual2);
const originalArgs = (_a = promiseRef.current) == null ? void 0 : _a.arg.originalArgs;
const finalState = useMemo(() => __spreadProps(__spreadValues({}, currentState), {
originalArgs
}), [currentState, originalArgs]);
return useMemo(() => [triggerMutation, finalState], [triggerMutation, finalState]);
};
}
}
// src/query/endpointDefinitions.ts
var DefinitionType;
(function (DefinitionType2) {
DefinitionType2["query"] = "query";
DefinitionType2["mutation"] = "mutation";
})(DefinitionType || (DefinitionType = {}));
function isQueryDefinition(e) {
return e.type === DefinitionType.query;
}
function isMutationDefinition(e) {
return e.type === DefinitionType.mutation;
}
// src/query/utils/capitalize.ts
function capitalize(str) {
return str.replace(str[0], str[0].toUpperCase());
}
// src/query/tsHelpers.ts
function safeAssign(target, ...args) {
Object.assign(target, ...args);
}
// src/query/react/module.ts
import { useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore, batch as rrBatch } from "react-redux";
var reactHooksModuleName = /* @__PURE__ */ Symbol();
var reactHooksModule = ({ batch = rrBatch, useDispatch = rrUseDispatch, useSelector = rrUseSelector, useStore = rrUseStore } = {}) => ({
name: reactHooksModuleName,
init(api, options, context) {
const anyApi = api;
const { buildQueryHooks, buildMutationHook, usePrefetch } = buildHooks({
api,
moduleOptions: { batch, useDispatch, useSelector, useStore }
});
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 } from "@reduxjs/toolkit";
import React from "react";
import { Provider } from "react-redux";
import { setupListeners } from "@reduxjs/toolkit/query";
function ApiProvider(props) {
const [store] = React.useState(() => configureStore({
reducer: {
[props.api.reducerPath]: props.api.reducer
},
middleware: (gDM) => gDM().concat(props.api.middleware)
}));
setupListeners(store.dispatch, props.setupListeners);
return /* @__PURE__ */ React.createElement(Provider, {
store,
context: props.context
}, props.children);
}
// src/query/react/index.ts
var createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule());
export { ApiProvider, createApi, reactHooksModule };
//# sourceMappingURL=module.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,324 @@
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));
// src/query/react/index.ts
import { coreModule, buildCreateApi } from "@reduxjs/toolkit/query";
// src/query/react/buildHooks.ts
import { createSelector } from "@reduxjs/toolkit";
import { useCallback, useEffect as useEffect2, useLayoutEffect, useMemo, useRef as useRef2, useState } from "react";
import { QueryStatus, skipToken } from "@reduxjs/toolkit/query";
import { shallowEqual as shallowEqual2 } from "react-redux";
// src/query/react/useShallowStableValue.ts
import { useEffect, useRef } from "react";
import { shallowEqual } from "react-redux";
function useShallowStableValue(value) {
const cache = useRef(value);
useEffect(() => {
if (!shallowEqual(cache.current, value)) {
cache.current = value;
}
}, [value]);
return shallowEqual(cache.current, value) ? cache.current : value;
}
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/buildHooks.ts
var useIsomorphicLayoutEffect = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined" ? useLayoutEffect : useEffect2;
var defaultQueryStateSelector = (x) => x;
var defaultMutationStateSelector = (x) => x;
var queryStatePreSelector = (currentState, lastResult) => {
var _a;
const data = (_a = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data) != null ? _a : currentState.data;
const isFetching = currentState.isLoading;
const isLoading = !data && isFetching;
const isSuccess = currentState.isSuccess || isFetching && !!data;
return __spreadProps(__spreadValues({}, currentState), {
data,
isFetching,
isLoading,
isSuccess
});
};
var noPendingQueryStateSelector = (selected) => {
if (selected.isUninitialized) {
return __spreadProps(__spreadValues({}, selected), {
isUninitialized: false,
isFetching: true,
isLoading: true,
status: QueryStatus.pending
});
}
return selected;
};
function buildHooks({ api, moduleOptions: { batch, useDispatch, useSelector, useStore } }) {
return { buildQueryHooks, buildMutationHook, usePrefetch };
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 } = {}) => {
const { initiate } = api.endpoints[name];
const dispatch = useDispatch();
const stableArg = useShallowStableValue(skip ? skipToken : arg);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval
});
const promiseRef = useRef2();
useEffect2(() => {
var _a;
const lastPromise = promiseRef.current;
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
]);
useEffect2(() => {
return () => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return useMemo(() => ({
refetch: () => {
var _a;
return void ((_a = promiseRef.current) == null ? void 0 : _a.refetch());
}
}), []);
};
const useLazyQuerySubscription = ({ refetchOnReconnect, refetchOnFocus, pollingInterval = 0 } = {}) => {
const { initiate } = api.endpoints[name];
const dispatch = useDispatch();
const [arg, setArg] = useState(UNINITIALIZED_VALUE);
const promiseRef = useRef2();
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval
});
useEffect2(() => {
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 = useRef2(stableSubscriptionOptions);
useEffect2(() => {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
const trigger = useCallback(function (arg2, preferCacheValue = false) {
batch(() => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
}, [dispatch, initiate]);
useEffect2(() => {
return () => {
var _a;
(_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
};
}, []);
useEffect2(() => {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return useMemo(() => [trigger, arg], [trigger, arg]);
};
const useQueryState = (arg, { skip = false, selectFromResult = defaultQueryStateSelector } = {}) => {
const { select } = api.endpoints[name];
const stableArg = useShallowStableValue(skip ? skipToken : arg);
const lastValue = useRef2();
const selectDefaultResult = useMemo(() => createSelector([select(stableArg), (_, lastResult) => lastResult], queryStatePreSelector), [select, stableArg]);
const querySelector = useMemo(() => createSelector([selectDefaultResult], selectFromResult), [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 = useMemo(() => ({ lastArg: arg }), [arg]);
return useMemo(() => [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));
return useMemo(() => __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults), [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return ({ selectFromResult = defaultMutationStateSelector } = {}) => {
var _a;
const { select, initiate } = api.endpoints[name];
const dispatch = useDispatch();
const [requestId, setRequestId] = useState();
const promiseRef = useRef2();
useEffect2(() => {
return () => {
var _a2;
(_a2 = promiseRef.current) == null ? void 0 : _a2.unsubscribe();
promiseRef.current = void 0;
};
}, []);
const triggerMutation = useCallback(function (arg) {
let promise;
batch(() => {
var _a2;
(_a2 = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a2.unsubscribe();
promise = dispatch(initiate(arg));
promiseRef.current = promise;
setRequestId(promise.requestId);
});
return promise;
}, [dispatch, initiate]);
const mutationSelector = useMemo(() => createSelector([select(requestId || skipToken)], (subState) => selectFromResult(subState)), [select, requestId, selectFromResult]);
const currentState = useSelector(mutationSelector, shallowEqual2);
const originalArgs = (_a = promiseRef.current) == null ? void 0 : _a.arg.originalArgs;
const finalState = useMemo(() => __spreadProps(__spreadValues({}, currentState), {
originalArgs
}), [currentState, originalArgs]);
return useMemo(() => [triggerMutation, finalState], [triggerMutation, finalState]);
};
}
}
// src/query/endpointDefinitions.ts
var DefinitionType;
(function (DefinitionType2) {
DefinitionType2["query"] = "query";
DefinitionType2["mutation"] = "mutation";
})(DefinitionType || (DefinitionType = {}));
function isQueryDefinition(e) {
return e.type === DefinitionType.query;
}
function isMutationDefinition(e) {
return e.type === DefinitionType.mutation;
}
// src/query/utils/capitalize.ts
function capitalize(str) {
return str.replace(str[0], str[0].toUpperCase());
}
// src/query/tsHelpers.ts
function safeAssign(target, ...args) {
Object.assign(target, ...args);
}
// src/query/react/module.ts
import { useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore, batch as rrBatch } from "react-redux";
var reactHooksModuleName = /* @__PURE__ */ Symbol();
var reactHooksModule = ({ batch = rrBatch, useDispatch = rrUseDispatch, useSelector = rrUseSelector, useStore = rrUseStore } = {}) => ({
name: reactHooksModuleName,
init(api, options, context) {
const anyApi = api;
const { buildQueryHooks, buildMutationHook, usePrefetch } = buildHooks({
api,
moduleOptions: { batch, useDispatch, useSelector, useStore }
});
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 } from "@reduxjs/toolkit";
import React from "react";
import { Provider } from "react-redux";
import { setupListeners } from "@reduxjs/toolkit/query";
function ApiProvider(props) {
const [store] = React.useState(() => configureStore({
reducer: {
[props.api.reducerPath]: props.api.reducer
},
middleware: (gDM) => gDM().concat(props.api.middleware)
}));
setupListeners(store.dispatch, props.setupListeners);
return /* @__PURE__ */ React.createElement(Provider, {
store,
context: props.context
}, props.children);
}
// src/query/react/index.ts
var createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule());
export { ApiProvider, createApi, reactHooksModule };
//# sourceMappingURL=module.js.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

File diff suppressed because it is too large Load diff

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 @@
export declare function useShallowStableValue<T>(value: T): T;

View file

@ -0,0 +1 @@
export { HooksWithUniqueNames } from './ts41Types';

View file

@ -0,0 +1,10 @@
{
"typesVersions": {
">=4.1": {
"index": ["./ts41Types.d.ts"]
},
"<4.1": {
"index": ["./ts40Types.d.ts"]
}
}
}

View file

@ -0,0 +1,3 @@
import type { EndpointDefinitions } from '@reduxjs/toolkit/dist/query/endpointDefinitions';
export declare type HooksWithUniqueNames<Definitions extends EndpointDefinitions> = unknown;
export {};

View file

@ -0,0 +1,13 @@
import type { UseMutation, UseLazyQuery, UseQuery } from '../buildHooks';
import type { DefinitionType, EndpointDefinitions, MutationDefinition, QueryDefinition } from '@reduxjs/toolkit/dist/query/endpointDefinitions';
export declare type HooksWithUniqueNames<Definitions extends EndpointDefinitions> = keyof Definitions extends infer Keys ? Keys extends string ? Definitions[Keys] extends {
type: DefinitionType.query;
} ? {
[K in Keys as `use${Capitalize<K>}Query`]: UseQuery<Extract<Definitions[K], QueryDefinition<any, any, any, any>>>;
} & {
[K in Keys as `useLazy${Capitalize<K>}Query`]: UseLazyQuery<Extract<Definitions[K], QueryDefinition<any, any, any, any>>>;
} : Definitions[Keys] extends {
type: DefinitionType.mutation;
} ? {
[K in Keys as `use${Capitalize<K>}Mutation`]: UseMutation<Extract<Definitions[K], MutationDefinition<any, any, any, any>>>;
} : never : never : never;