planning
All checks were successful
Publish To Prod / deploy_and_publish (push) Successful in 35s

This commit is contained in:
2024-10-14 09:15:30 +02:00
parent bcba00a730
commit 6e64e138e2
21059 changed files with 2317811 additions and 1 deletions

View File

@@ -0,0 +1,5 @@
export declare class HandledError {
readonly value: any;
readonly meta: any;
constructor(value: any, meta?: any);
}

41
node_modules/@reduxjs/toolkit/dist/query/apiTypes.d.ts generated vendored Normal file
View File

@@ -0,0 +1,41 @@
import type { EndpointDefinitions, EndpointBuilder, EndpointDefinition, UpdateDefinitions } from './endpointDefinitions';
import type { UnionToIntersection, NoInfer, WithRequiredProp } from './tsHelpers';
import type { CoreModule } from './core/module';
import type { CreateApiOptions } from './createApi';
import type { BaseQueryFn } from './baseQueryTypes';
import type { CombinedState } from './core/apiState';
import type { AnyAction } from '@reduxjs/toolkit';
export interface ApiModules<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {
}
export declare type ModuleName = keyof ApiModules<any, any, any, any>;
export declare type Module<Name extends ModuleName> = {
name: Name;
init<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string>(api: Api<BaseQuery, EndpointDefinitions, ReducerPath, TagTypes, ModuleName>, options: WithRequiredProp<CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>, 'reducerPath' | 'serializeQueryArgs' | 'keepUnusedDataFor' | 'refetchOnMountOrArgChange' | 'refetchOnFocus' | 'refetchOnReconnect' | 'tagTypes'>, context: ApiContext<Definitions>): {
injectEndpoint(endpointName: string, definition: EndpointDefinition<any, any, any, any>): void;
};
};
export interface ApiContext<Definitions extends EndpointDefinitions> {
apiUid: string;
endpointDefinitions: Definitions;
batch(cb: () => void): void;
extractRehydrationInfo: (action: AnyAction) => CombinedState<any, any, any> | undefined;
hasRehydrationInfo: (action: AnyAction) => boolean;
}
export declare type Api<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string, Enhancers extends ModuleName = CoreModule> = UnionToIntersection<ApiModules<BaseQuery, Definitions, ReducerPath, TagTypes>[Enhancers]> & {
/**
* A function to inject the endpoints into the original API, but also give you that same API with correct types for these endpoints back. Useful with code-splitting.
*/
injectEndpoints<NewDefinitions extends EndpointDefinitions>(_: {
endpoints: (build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>) => NewDefinitions;
overrideExisting?: boolean;
}): Api<BaseQuery, Definitions & NewDefinitions, ReducerPath, TagTypes, Enhancers>;
/**
*A function to enhance a generated API with additional information. Useful with code-generation.
*/
enhanceEndpoints<NewTagTypes extends string = never, NewDefinitions extends EndpointDefinitions = never>(_: {
addTagTypes?: readonly NewTagTypes[];
endpoints?: UpdateDefinitions<Definitions, TagTypes | NoInfer<NewTagTypes>, NewDefinitions> extends infer NewDefinitions ? {
[K in keyof NewDefinitions]?: Partial<NewDefinitions[K]> | ((definition: NewDefinitions[K]) => void);
} : never;
}): Api<BaseQuery, UpdateDefinitions<Definitions, TagTypes | NewTagTypes, NewDefinitions>, ReducerPath, TagTypes | NewTagTypes, Enhancers>;
};

View File

@@ -0,0 +1,40 @@
import type { ThunkDispatch } from '@reduxjs/toolkit';
import type { MaybePromise, UnwrapPromise } from './tsHelpers';
export interface BaseQueryApi {
signal: AbortSignal;
abort: (reason?: string) => void;
dispatch: ThunkDispatch<any, any, any>;
getState: () => unknown;
extra: unknown;
endpoint: string;
type: 'query' | 'mutation';
/**
* Only available for queries: indicates if a query has been forced,
* i.e. it would have been fetched even if there would already be a cache entry
* (this does not mean that there is already a cache entry though!)
*
* This can be used to for example add a `Cache-Control: no-cache` header for
* invalidated queries.
*/
forced?: boolean;
}
export declare type QueryReturnValue<T = unknown, E = unknown, M = unknown> = {
error: E;
data?: undefined;
meta?: M;
} | {
error?: undefined;
data: T;
meta?: M;
};
export declare type BaseQueryFn<Args = any, Result = unknown, Error = unknown, DefinitionExtraOptions = {}, Meta = {}> = (args: Args, api: BaseQueryApi, extraOptions: DefinitionExtraOptions) => MaybePromise<QueryReturnValue<Result, Error, Meta>>;
export declare type BaseQueryEnhancer<AdditionalArgs = unknown, AdditionalDefinitionExtraOptions = unknown, Config = void> = <BaseQuery extends BaseQueryFn>(baseQuery: BaseQuery, config: Config) => BaseQueryFn<BaseQueryArg<BaseQuery> & AdditionalArgs, BaseQueryResult<BaseQuery>, BaseQueryError<BaseQuery>, BaseQueryExtraOptions<BaseQuery> & AdditionalDefinitionExtraOptions, NonNullable<BaseQueryMeta<BaseQuery>>>;
export declare type BaseQueryResult<BaseQuery extends BaseQueryFn> = UnwrapPromise<ReturnType<BaseQuery>> extends infer Unwrapped ? Unwrapped extends {
data: any;
} ? Unwrapped['data'] : never : never;
export declare type BaseQueryMeta<BaseQuery extends BaseQueryFn> = UnwrapPromise<ReturnType<BaseQuery>>['meta'];
export declare type BaseQueryError<BaseQuery extends BaseQueryFn> = Exclude<UnwrapPromise<ReturnType<BaseQuery>>, {
error?: undefined;
}>['error'];
export declare type BaseQueryArg<T extends (arg: any, ...args: any[]) => any> = T extends (arg: infer A, ...args: any[]) => any ? A : any;
export declare type BaseQueryExtraOptions<BaseQuery extends BaseQueryFn> = Parameters<BaseQuery>[2];

View File

@@ -0,0 +1,198 @@
import type { SerializedError } from '@reduxjs/toolkit';
import type { BaseQueryError } from '../baseQueryTypes';
import type { QueryDefinition, MutationDefinition, EndpointDefinitions, BaseEndpointDefinition, ResultTypeFrom, QueryArgFrom } from '../endpointDefinitions';
import type { Id, WithRequiredProp } from '../tsHelpers';
export declare type QueryCacheKey = string & {
_type: 'queryCacheKey';
};
export declare type QuerySubstateIdentifier = {
queryCacheKey: QueryCacheKey;
};
export declare type MutationSubstateIdentifier = {
requestId: string;
fixedCacheKey?: string;
} | {
requestId?: string;
fixedCacheKey: string;
};
export declare type RefetchConfigOptions = {
refetchOnMountOrArgChange: boolean | number;
refetchOnReconnect: boolean;
refetchOnFocus: boolean;
};
/**
* Strings describing the query state at any given time.
*/
export declare enum QueryStatus {
uninitialized = "uninitialized",
pending = "pending",
fulfilled = "fulfilled",
rejected = "rejected"
}
export declare type RequestStatusFlags = {
status: QueryStatus.uninitialized;
isUninitialized: true;
isLoading: false;
isSuccess: false;
isError: false;
} | {
status: QueryStatus.pending;
isUninitialized: false;
isLoading: true;
isSuccess: false;
isError: false;
} | {
status: QueryStatus.fulfilled;
isUninitialized: false;
isLoading: false;
isSuccess: true;
isError: false;
} | {
status: QueryStatus.rejected;
isUninitialized: false;
isLoading: false;
isSuccess: false;
isError: true;
};
export declare function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags;
export declare type SubscriptionOptions = {
/**
* How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).
*/
pollingInterval?: number;
/**
* Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*
* Note: requires [`setupListeners`](./setupListeners) to have been called.
*/
refetchOnReconnect?: boolean;
/**
* Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*
* Note: requires [`setupListeners`](./setupListeners) to have been called.
*/
refetchOnFocus?: boolean;
};
export declare type Subscribers = {
[requestId: string]: SubscriptionOptions;
};
export declare type QueryKeys<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any> ? K : never;
}[keyof Definitions];
export declare type MutationKeys<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions]: Definitions[K] extends MutationDefinition<any, any, any, any> ? K : never;
}[keyof Definitions];
declare type BaseQuerySubState<D extends BaseEndpointDefinition<any, any, any>> = {
/**
* The argument originally passed into the hook or `initiate` action call
*/
originalArgs: QueryArgFrom<D>;
/**
* A unique ID associated with the request
*/
requestId: string;
/**
* The received data from the query
*/
data?: ResultTypeFrom<D>;
/**
* The received error if applicable
*/
error?: SerializedError | (D extends QueryDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);
/**
* The name of the endpoint associated with the query
*/
endpointName: string;
/**
* Time that the latest query started
*/
startedTimeStamp: number;
/**
* Time that the latest query was fulfilled
*/
fulfilledTimeStamp?: number;
};
export declare type QuerySubState<D extends BaseEndpointDefinition<any, any, any>> = Id<({
status: QueryStatus.fulfilled;
} & WithRequiredProp<BaseQuerySubState<D>, 'data' | 'fulfilledTimeStamp'> & {
error: undefined;
}) | ({
status: QueryStatus.pending;
} & BaseQuerySubState<D>) | ({
status: QueryStatus.rejected;
} & WithRequiredProp<BaseQuerySubState<D>, 'error'>) | {
status: QueryStatus.uninitialized;
originalArgs?: undefined;
data?: undefined;
error?: undefined;
requestId?: undefined;
endpointName?: string;
startedTimeStamp?: undefined;
fulfilledTimeStamp?: undefined;
}>;
declare type BaseMutationSubState<D extends BaseEndpointDefinition<any, any, any>> = {
requestId: string;
data?: ResultTypeFrom<D>;
error?: SerializedError | (D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);
endpointName: string;
startedTimeStamp: number;
fulfilledTimeStamp?: number;
};
export declare type MutationSubState<D extends BaseEndpointDefinition<any, any, any>> = (({
status: QueryStatus.fulfilled;
} & WithRequiredProp<BaseMutationSubState<D>, 'data' | 'fulfilledTimeStamp'>) & {
error: undefined;
}) | (({
status: QueryStatus.pending;
} & BaseMutationSubState<D>) & {
data?: undefined;
}) | ({
status: QueryStatus.rejected;
} & WithRequiredProp<BaseMutationSubState<D>, 'error'>) | {
requestId?: undefined;
status: QueryStatus.uninitialized;
data?: undefined;
error?: undefined;
endpointName?: string;
startedTimeStamp?: undefined;
fulfilledTimeStamp?: undefined;
};
export declare type CombinedState<D extends EndpointDefinitions, E extends string, ReducerPath extends string> = {
queries: QueryState<D>;
mutations: MutationState<D>;
provided: InvalidationState<E>;
subscriptions: SubscriptionState;
config: ConfigState<ReducerPath>;
};
export declare type InvalidationState<TagTypes extends string> = {
[_ in TagTypes]: {
[id: string]: Array<QueryCacheKey>;
[id: number]: Array<QueryCacheKey>;
};
};
export declare type QueryState<D extends EndpointDefinitions> = {
[queryCacheKey: string]: QuerySubState<D[string]> | undefined;
};
export declare type SubscriptionState = {
[queryCacheKey: string]: Subscribers | undefined;
};
export declare type ConfigState<ReducerPath> = RefetchConfigOptions & {
reducerPath: ReducerPath;
online: boolean;
focused: boolean;
middlewareRegistered: boolean | 'conflict';
} & ModifiableConfigState;
export declare type ModifiableConfigState = {
keepUnusedDataFor: number;
} & RefetchConfigOptions;
export declare type MutationState<D extends EndpointDefinitions> = {
[requestId: string]: MutationSubState<D[string]> | undefined;
};
export declare type RootState<Definitions extends EndpointDefinitions, TagTypes extends string, ReducerPath extends string> = {
[P in ReducerPath]: CombinedState<Definitions, TagTypes, P>;
};
export {};

View File

@@ -0,0 +1,152 @@
import type { EndpointDefinitions, QueryDefinition, MutationDefinition, QueryArgFrom, ResultTypeFrom } from '../endpointDefinitions';
import type { QueryThunk, MutationThunk, QueryThunkArg } from './buildThunks';
import type { AnyAction, ThunkAction, SerializedError } from '@reduxjs/toolkit';
import type { SubscriptionOptions } from './apiState';
import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';
import type { Api, ApiContext } from '../apiTypes';
import type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes';
import type { QueryResultSelectorResult } from './buildSelectors';
import type { Dispatch } from 'redux';
declare module './module' {
interface ApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
initiate: StartQueryActionCreator<Definition>;
}
interface ApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
initiate: StartMutationActionCreator<Definition>;
}
}
export declare const forceQueryFnSymbol: unique symbol;
export declare const isUpsertQuery: (arg: QueryThunkArg) => boolean;
export interface StartQueryActionCreatorOptions {
subscribe?: boolean;
forceRefetch?: boolean | number;
subscriptionOptions?: SubscriptionOptions;
[forceQueryFnSymbol]?: () => QueryReturnValue;
}
declare type StartQueryActionCreator<D extends QueryDefinition<any, any, any, any, any>> = (arg: QueryArgFrom<D>, options?: StartQueryActionCreatorOptions) => ThunkAction<QueryActionCreatorResult<D>, any, any, AnyAction>;
export declare type QueryActionCreatorResult<D extends QueryDefinition<any, any, any, any>> = Promise<QueryResultSelectorResult<D>> & {
arg: QueryArgFrom<D>;
requestId: string;
subscriptionOptions: SubscriptionOptions | undefined;
abort(): void;
unwrap(): Promise<ResultTypeFrom<D>>;
unsubscribe(): void;
refetch(): QueryActionCreatorResult<D>;
updateSubscriptionOptions(options: SubscriptionOptions): void;
queryCacheKey: string;
};
declare type StartMutationActionCreator<D extends MutationDefinition<any, any, any, any>> = (arg: QueryArgFrom<D>, options?: {
/**
* If this mutation should be tracked in the store.
* If you just want to manually trigger this mutation using `dispatch` and don't care about the
* result, state & potential errors being held in store, you can set this to false.
* (defaults to `true`)
*/
track?: boolean;
fixedCacheKey?: string;
}) => ThunkAction<MutationActionCreatorResult<D>, any, any, AnyAction>;
export declare type MutationActionCreatorResult<D extends MutationDefinition<any, any, any, any>> = Promise<{
data: ResultTypeFrom<D>;
} | {
error: Exclude<BaseQueryError<D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQuery : never>, undefined> | SerializedError;
}> & {
/** @internal */
arg: {
/**
* The name of the given endpoint for the mutation
*/
endpointName: string;
/**
* The original arguments supplied to the mutation call
*/
originalArgs: QueryArgFrom<D>;
/**
* Whether the mutation is being tracked in the store.
*/
track?: boolean;
fixedCacheKey?: string;
};
/**
* A unique string generated for the request sequence
*/
requestId: string;
/**
* A method to cancel the mutation promise. Note that this is not intended to prevent the mutation
* that was fired off from reaching the server, but only to assist in handling the response.
*
* Calling `abort()` prior to the promise resolving will force it to reach the error state with
* the serialized error:
* `{ name: 'AbortError', message: 'Aborted' }`
*
* @example
* ```ts
* const [updateUser] = useUpdateUserMutation();
*
* useEffect(() => {
* const promise = updateUser(id);
* promise
* .unwrap()
* .catch((err) => {
* if (err.name === 'AbortError') return;
* // else handle the unexpected error
* })
*
* return () => {
* promise.abort();
* }
* }, [id, updateUser])
* ```
*/
abort(): void;
/**
* Unwraps a mutation call to provide the raw response/error.
*
* @remarks
* If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap"
* addPost({ id: 1, name: 'Example' })
* .unwrap()
* .then((payload) => console.log('fulfilled', payload))
* .catch((error) => console.error('rejected', error));
* ```
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap with async await"
* try {
* const payload = await addPost({ id: 1, name: 'Example' }).unwrap();
* console.log('fulfilled', payload)
* } catch (error) {
* console.error('rejected', error);
* }
* ```
*/
unwrap(): Promise<ResultTypeFrom<D>>;
/**
* A method to manually unsubscribe from the mutation call, meaning it will be removed from cache after the usual caching grace period.
The value returned by the hook will reset to `isUninitialized` afterwards.
*/
reset(): void;
/** @deprecated has been renamed to `reset` */
unsubscribe(): void;
};
export declare function buildInitiate({ serializeQueryArgs, queryThunk, mutationThunk, api, context, }: {
serializeQueryArgs: InternalSerializeQueryArgs;
queryThunk: QueryThunk;
mutationThunk: MutationThunk;
api: Api<any, EndpointDefinitions, any, any>;
context: ApiContext<EndpointDefinitions>;
}): {
buildInitiateQuery: (endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) => StartQueryActionCreator<any>;
buildInitiateMutation: (endpointName: string) => StartMutationActionCreator<any>;
getRunningQueryThunk: (endpointName: string, queryArgs: any) => (dispatch: Dispatch) => QueryActionCreatorResult<never> | undefined;
getRunningMutationThunk: (_endpointName: string, fixedCacheKeyOrRequestId: string) => (dispatch: Dispatch) => MutationActionCreatorResult<never> | undefined;
getRunningQueriesThunk: () => (dispatch: Dispatch) => QueryActionCreatorResult<any>[];
getRunningMutationsThunk: () => (dispatch: Dispatch) => MutationActionCreatorResult<any>[];
getRunningOperationPromises: () => (QueryActionCreatorResult<any> | MutationActionCreatorResult<any>)[];
removalWarning: () => never;
};
export {};

View File

@@ -0,0 +1,5 @@
import type { InternalHandlerBuilder } from './types';
export declare const buildBatchedActionsHandler: InternalHandlerBuilder<[
actionShouldContinue: boolean,
subscriptionExists: boolean
]>;

View File

@@ -0,0 +1,16 @@
import type { BaseQueryFn } from '../../baseQueryTypes';
import type { InternalHandlerBuilder } from './types';
export declare type ReferenceCacheCollection = never;
declare module '../../endpointDefinitions' {
interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> {
/**
* Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(This value is in seconds.)_
*
* This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.
*/
keepUnusedDataFor?: number;
}
}
export declare const THIRTY_TWO_BIT_MAX_INT = 2147483647;
export declare const THIRTY_TWO_BIT_MAX_TIMER_SECONDS: number;
export declare const buildCacheCollectionHandler: InternalHandlerBuilder;

View File

@@ -0,0 +1,95 @@
import type { AnyAction } from 'redux';
import type { ThunkDispatch } from 'redux-thunk';
import type { BaseQueryFn, BaseQueryMeta } from '../../baseQueryTypes';
import type { RootState } from '../apiState';
import type { MutationResultSelectorResult, QueryResultSelectorResult } from '../buildSelectors';
import type { PatchCollection, Recipe } from '../buildThunks';
import type { InternalHandlerBuilder, PromiseWithKnownReason } from './types';
export declare type ReferenceCacheLifecycle = never;
declare module '../../endpointDefinitions' {
interface QueryBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends LifecycleApi<ReducerPath> {
/**
* Gets the current value of this cache entry.
*/
getCacheEntry(): QueryResultSelectorResult<{
type: DefinitionType.query;
} & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType>>;
/**
* Updates the current cache entry value.
* For documentation see `api.util.updateQueryData`.
*/
updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection;
}
interface MutationBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends LifecycleApi<ReducerPath> {
/**
* Gets the current value of this cache entry.
*/
getCacheEntry(): MutationResultSelectorResult<{
type: DefinitionType.mutation;
} & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType>>;
}
interface LifecycleApi<ReducerPath extends string = string> {
/**
* The dispatch method for the store
*/
dispatch: ThunkDispatch<any, any, AnyAction>;
/**
* A method to get the current state
*/
getState(): RootState<any, any, ReducerPath>;
/**
* `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.
*/
extra: unknown;
/**
* A unique ID generated for the mutation
*/
requestId: string;
}
interface CacheLifecyclePromises<ResultType = unknown, MetaType = unknown> {
/**
* Promise that will resolve with the first value for this cache key.
* This allows you to `await` until an actual value is in cache.
*
* If the cache entry is removed from the cache before any value has ever
* been resolved, this Promise will reject with
* `new Error('Promise never resolved before cacheEntryRemoved.')`
* to prevent memory leaks.
* You can just re-throw that error (or not handle it at all) -
* it will be caught outside of `cacheEntryAdded`.
*
* If you don't interact with this promise, it will not throw.
*/
cacheDataLoaded: PromiseWithKnownReason<{
/**
* The (transformed) query result.
*/
data: ResultType;
/**
* The `meta` returned by the `baseQuery`
*/
meta: MetaType;
}, typeof neverResolvedError>;
/**
* Promise that allows you to wait for the point in time when the cache entry
* has been removed from the cache, by not being used/subscribed to any more
* in the application for too long or by dispatching `api.util.resetApiState`.
*/
cacheEntryRemoved: Promise<void>;
}
interface QueryCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {
}
interface MutationCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {
}
interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> {
onCacheEntryAdded?(arg: QueryArg, api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;
}
interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> {
onCacheEntryAdded?(arg: QueryArg, api: MutationCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;
}
}
declare const neverResolvedError: Error & {
message: 'Promise never resolved before cacheEntryRemoved.';
};
export declare const buildCacheLifecycleHandler: InternalHandlerBuilder;
export {};

View File

@@ -0,0 +1,2 @@
import type { InternalHandlerBuilder } from './types';
export declare const buildDevCheckHandler: InternalHandlerBuilder;

View File

@@ -0,0 +1,10 @@
import type { AnyAction, Middleware, ThunkDispatch } from '@reduxjs/toolkit';
import type { EndpointDefinitions, FullTagDescription } from '../../endpointDefinitions';
import type { RootState } from '../apiState';
import type { BuildMiddlewareInput } from './types';
export declare function buildMiddleware<Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string>(input: BuildMiddlewareInput<Definitions, ReducerPath, TagTypes>): {
middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, AnyAction>>;
actions: {
invalidateTags: import("@reduxjs/toolkit").ActionCreatorWithPayload<(TagTypes | FullTagDescription<TagTypes>)[], string>;
};
};

View File

@@ -0,0 +1,2 @@
import type { InternalHandlerBuilder } from './types';
export declare const buildInvalidationByTagsHandler: InternalHandlerBuilder;

View File

@@ -0,0 +1,2 @@
import type { InternalHandlerBuilder } from './types';
export declare const buildPollingHandler: InternalHandlerBuilder;

View File

@@ -0,0 +1,142 @@
import type { BaseQueryError, BaseQueryFn, BaseQueryMeta } from '../../baseQueryTypes';
import type { PromiseWithKnownReason, InternalHandlerBuilder } from './types';
export declare type ReferenceQueryLifecycle = never;
declare module '../../endpointDefinitions' {
interface QueryLifecyclePromises<ResultType, BaseQuery extends BaseQueryFn> {
/**
* Promise that will resolve with the (transformed) query result.
*
* If the query fails, this promise will reject with the error.
*
* This allows you to `await` for the query to finish.
*
* If you don't interact with this promise, it will not throw.
*/
queryFulfilled: PromiseWithKnownReason<{
/**
* The (transformed) query result.
*/
data: ResultType;
/**
* The `meta` returned by the `baseQuery`
*/
meta: BaseQueryMeta<BaseQuery>;
}, QueryFulfilledRejectionReason<BaseQuery>>;
}
type QueryFulfilledRejectionReason<BaseQuery extends BaseQueryFn> = {
error: BaseQueryError<BaseQuery>;
/**
* If this is `false`, that means this error was returned from the `baseQuery` or `queryFn` in a controlled manner.
*/
isUnhandledError: false;
/**
* The `meta` returned by the `baseQuery`
*/
meta: BaseQueryMeta<BaseQuery>;
} | {
error: unknown;
meta?: undefined;
/**
* If this is `true`, that means that this error is the result of `baseQueryFn`, `queryFn`, `transformResponse` or `transformErrorResponse` throwing an error instead of handling it properly.
* There can not be made any assumption about the shape of `error`.
*/
isUnhandledError: true;
};
interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> {
/**
* A function that is called when the individual query is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).
*
* Can be used to perform side-effects throughout the lifecycle of the query.
*
* @example
* ```ts
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
* import { messageCreated } from './notificationsSlice
* export interface Post {
* id: number
* name: string
* }
*
* const api = createApi({
* baseQuery: fetchBaseQuery({
* baseUrl: '/',
* }),
* endpoints: (build) => ({
* getPost: build.query<Post, number>({
* query: (id) => `post/${id}`,
* async onQueryStarted(id, { dispatch, queryFulfilled }) {
* // `onStart` side-effect
* dispatch(messageCreated('Fetching posts...'))
* try {
* const { data } = await queryFulfilled
* // `onSuccess` side-effect
* dispatch(messageCreated('Posts received!'))
* } catch (err) {
* // `onError` side-effect
* dispatch(messageCreated('Error fetching posts!'))
* }
* }
* }),
* }),
* })
* ```
*/
onQueryStarted?(arg: QueryArg, api: QueryLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;
}
interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> {
/**
* A function that is called when the individual mutation is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).
*
* Can be used for `optimistic updates`.
*
* @example
*
* ```ts
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
* export interface Post {
* id: number
* name: string
* }
*
* const api = createApi({
* baseQuery: fetchBaseQuery({
* baseUrl: '/',
* }),
* tagTypes: ['Post'],
* endpoints: (build) => ({
* getPost: build.query<Post, number>({
* query: (id) => `post/${id}`,
* providesTags: ['Post'],
* }),
* updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
* query: ({ id, ...patch }) => ({
* url: `post/${id}`,
* method: 'PATCH',
* body: patch,
* }),
* invalidatesTags: ['Post'],
* async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
* const patchResult = dispatch(
* api.util.updateQueryData('getPost', id, (draft) => {
* Object.assign(draft, patch)
* })
* )
* try {
* await queryFulfilled
* } catch {
* patchResult.undo()
* }
* },
* }),
* }),
* })
* ```
*/
onQueryStarted?(arg: QueryArg, api: MutationLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;
}
interface QueryLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, QueryLifecyclePromises<ResultType, BaseQuery> {
}
interface MutationLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, QueryLifecyclePromises<ResultType, BaseQuery> {
}
}
export declare const buildQueryLifecycleHandler: InternalHandlerBuilder;

View File

@@ -0,0 +1,54 @@
import type { AnyAction, AsyncThunkAction, Dispatch, Middleware, MiddlewareAPI, ThunkDispatch } from '@reduxjs/toolkit';
import type { Api, ApiContext } from '../../apiTypes';
import type { AssertTagTypes, EndpointDefinitions } from '../../endpointDefinitions';
import type { QueryStatus, QuerySubState, RootState, SubscriptionState } from '../apiState';
import type { MutationThunk, QueryThunk, QueryThunkArg, ThunkResult } from '../buildThunks';
export declare type QueryStateMeta<T> = Record<string, undefined | T>;
export declare type TimeoutId = ReturnType<typeof setTimeout>;
export interface InternalMiddlewareState {
currentSubscriptions: SubscriptionState;
}
export interface BuildMiddlewareInput<Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {
reducerPath: ReducerPath;
context: ApiContext<Definitions>;
queryThunk: QueryThunk;
mutationThunk: MutationThunk;
api: Api<any, Definitions, ReducerPath, TagTypes>;
assertTagType: AssertTagTypes;
}
export declare type SubMiddlewareApi = MiddlewareAPI<ThunkDispatch<any, any, AnyAction>, RootState<EndpointDefinitions, string, string>>;
export interface BuildSubMiddlewareInput extends BuildMiddlewareInput<EndpointDefinitions, string, string> {
internalState: InternalMiddlewareState;
refetchQuery(querySubState: Exclude<QuerySubState<any>, {
status: QueryStatus.uninitialized;
}>, queryCacheKey: string, override?: Partial<QueryThunkArg>): AsyncThunkAction<ThunkResult, QueryThunkArg, {}>;
}
export declare type SubMiddlewareBuilder = (input: BuildSubMiddlewareInput) => Middleware<{}, RootState<EndpointDefinitions, string, string>, ThunkDispatch<any, any, AnyAction>>;
export declare type ApiMiddlewareInternalHandler<ReturnType = void> = (action: AnyAction, mwApi: SubMiddlewareApi & {
next: Dispatch<AnyAction>;
}, prevState: RootState<EndpointDefinitions, string, string>) => ReturnType;
export declare type InternalHandlerBuilder<ReturnType = void> = (input: BuildSubMiddlewareInput) => ApiMiddlewareInternalHandler<ReturnType>;
export interface PromiseConstructorWithKnownReason {
/**
* Creates a new Promise with a known rejection reason.
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used to resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
new <T, R>(executor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: R) => void) => void): PromiseWithKnownReason<T, R>;
}
export interface PromiseWithKnownReason<T, R> extends Omit<Promise<T>, 'then' | 'catch'> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: R) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch<TResult = never>(onrejected?: ((reason: R) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}

View File

@@ -0,0 +1,2 @@
import type { InternalHandlerBuilder } from './types';
export declare const buildWindowEventHandler: InternalHandlerBuilder;

View File

@@ -0,0 +1,63 @@
import type { MutationSubState, QuerySubState, RootState as _RootState, RequestStatusFlags, QueryCacheKey } from './apiState';
import type { EndpointDefinitions, QueryDefinition, MutationDefinition, QueryArgFrom, TagTypesFrom, ReducerPathFrom, TagDescription } from '../endpointDefinitions';
import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';
export declare type SkipToken = typeof skipToken;
/**
* Can be passed into `useQuery`, `useQueryState` or `useQuerySubscription`
* instead of the query argument to get the same effect as if setting
* `skip: true` in the query options.
*
* Useful for scenarios where a query should be skipped when `arg` is `undefined`
* and TypeScript complains about it because `arg` is not allowed to be passed
* in as `undefined`, such as
*
* ```ts
* // codeblock-meta title="will error if the query argument is not allowed to be undefined" no-transpile
* useSomeQuery(arg, { skip: !!arg })
* ```
*
* ```ts
* // codeblock-meta title="using skipToken instead" no-transpile
* useSomeQuery(arg ?? skipToken)
* ```
*
* If passed directly into a query or mutation selector, that selector will always
* return an uninitialized state.
*/
export declare const skipToken: unique symbol;
/** @deprecated renamed to `skipToken` */
export declare const skipSelector: symbol;
declare module './module' {
interface ApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
select: QueryResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;
}
interface ApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
select: MutationResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;
}
}
declare type QueryResultSelectorFactory<Definition extends QueryDefinition<any, any, any, any>, RootState> = (queryArg: QueryArgFrom<Definition> | SkipToken) => (state: RootState) => QueryResultSelectorResult<Definition>;
export declare type QueryResultSelectorResult<Definition extends QueryDefinition<any, any, any, any>> = QuerySubState<Definition> & RequestStatusFlags;
declare type MutationResultSelectorFactory<Definition extends MutationDefinition<any, any, any, any>, RootState> = (requestId: string | {
requestId: string | undefined;
fixedCacheKey: string | undefined;
} | SkipToken) => (state: RootState) => MutationResultSelectorResult<Definition>;
export declare type MutationResultSelectorResult<Definition extends MutationDefinition<any, any, any, any>> = MutationSubState<Definition> & RequestStatusFlags;
export declare function buildSelectors<Definitions extends EndpointDefinitions, ReducerPath extends string>({ serializeQueryArgs, reducerPath, }: {
serializeQueryArgs: InternalSerializeQueryArgs;
reducerPath: ReducerPath;
}): {
buildQuerySelector: (endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) => QueryResultSelectorFactory<any, {
[x: string]: import("./apiState").CombinedState<Definitions, string, string>;
}>;
buildMutationSelector: () => MutationResultSelectorFactory<any, {
[x: string]: import("./apiState").CombinedState<Definitions, string, string>;
}>;
selectInvalidatedBy: (state: {
[x: string]: import("./apiState").CombinedState<Definitions, string, string>;
}, tags: ReadonlyArray<TagDescription<string>>) => Array<{
endpointName: string;
originalArgs: any;
queryCacheKey: QueryCacheKey;
}>;
};
export {};

View File

@@ -0,0 +1,60 @@
import type { AnyAction } from '@reduxjs/toolkit';
import type { CombinedState as CombinedQueryState, QuerySubstateIdentifier, MutationSubstateIdentifier, Subscribers, QueryCacheKey, ConfigState } from './apiState';
import type { MutationThunk, QueryThunk } from './buildThunks';
import type { AssertTagTypes, EndpointDefinitions, FullTagDescription } from '../endpointDefinitions';
import type { Patch } from 'immer';
import type { ApiContext } from '../apiTypes';
export declare function getMutationCacheKey(id: MutationSubstateIdentifier | {
requestId: string;
arg: {
fixedCacheKey?: string | undefined;
};
}): string;
export declare function getMutationCacheKey(id: {
fixedCacheKey?: string;
requestId?: string;
}): string | undefined;
export declare function buildSlice({ reducerPath, queryThunk, mutationThunk, context: { endpointDefinitions: definitions, apiUid, extractRehydrationInfo, hasRehydrationInfo, }, assertTagType, config, }: {
reducerPath: string;
queryThunk: QueryThunk;
mutationThunk: MutationThunk;
context: ApiContext<EndpointDefinitions>;
assertTagType: AssertTagTypes;
config: Omit<ConfigState<string>, 'online' | 'focused' | 'middlewareRegistered'>;
}): {
reducer: import("redux").Reducer<import("redux").CombinedState<CombinedQueryState<any, string, string>>, AnyAction>;
actions: {
/** @deprecated has been renamed to `removeMutationResult` */
unsubscribeMutationResult: import("@reduxjs/toolkit").ActionCreatorWithPreparedPayload<[payload: MutationSubstateIdentifier], MutationSubstateIdentifier, `${string}/removeMutationResult`, never, unknown>;
resetApiState: import("@reduxjs/toolkit").ActionCreatorWithoutPayload<string>;
updateProvidedBy: import("@reduxjs/toolkit").ActionCreatorWithPreparedPayload<[payload: {
queryCacheKey: QueryCacheKey;
providedTags: readonly FullTagDescription<string>[];
}], {
queryCacheKey: QueryCacheKey;
providedTags: readonly FullTagDescription<string>[];
}, `${string}/updateProvidedBy`, never, unknown>;
removeMutationResult: import("@reduxjs/toolkit").ActionCreatorWithPreparedPayload<[payload: MutationSubstateIdentifier], MutationSubstateIdentifier, `${string}/removeMutationResult`, never, unknown>;
subscriptionsUpdated: import("@reduxjs/toolkit").ActionCreatorWithPreparedPayload<[payload: Patch[]], Patch[], `${string}/subscriptionsUpdated`, never, unknown>;
updateSubscriptionOptions: import("@reduxjs/toolkit").ActionCreatorWithPayload<{
endpointName: string;
requestId: string;
options: Subscribers[number];
} & QuerySubstateIdentifier, `${string}/updateSubscriptionOptions`>;
unsubscribeQueryResult: import("@reduxjs/toolkit").ActionCreatorWithPayload<{
requestId: string;
} & QuerySubstateIdentifier, `${string}/unsubscribeQueryResult`>;
internal_probeSubscription: import("@reduxjs/toolkit").ActionCreatorWithPayload<{
queryCacheKey: string;
requestId: string;
}, `${string}/internal_probeSubscription`>;
removeQueryResult: import("@reduxjs/toolkit").ActionCreatorWithPreparedPayload<[payload: QuerySubstateIdentifier], QuerySubstateIdentifier, `${string}/removeQueryResult`, never, unknown>;
queryResultPatched: import("@reduxjs/toolkit").ActionCreatorWithPreparedPayload<[payload: QuerySubstateIdentifier & {
patches: readonly Patch[];
}], QuerySubstateIdentifier & {
patches: readonly Patch[];
}, `${string}/queryResultPatched`, never, unknown>;
middlewareRegistered: import("@reduxjs/toolkit").ActionCreatorWithPayload<string, `${string}/middlewareRegistered`>;
};
};
export declare type SliceActions = ReturnType<typeof buildSlice>['actions'];

View File

@@ -0,0 +1,141 @@
import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';
import type { Api, ApiContext } from '../apiTypes';
import type { BaseQueryFn, BaseQueryError } from '../baseQueryTypes';
import type { RootState, QueryKeys, QuerySubstateIdentifier } from './apiState';
import type { StartQueryActionCreatorOptions, QueryActionCreatorResult } from './buildInitiate';
import type { AssertTagTypes, EndpointDefinition, EndpointDefinitions, MutationDefinition, QueryArgFrom, QueryDefinition, ResultTypeFrom, FullTagDescription } from '../endpointDefinitions';
import type { Draft } from '@reduxjs/toolkit';
import type { Patch } from 'immer';
import type { AnyAction, ThunkAction, AsyncThunk } from '@reduxjs/toolkit';
import { SHOULD_AUTOBATCH } from '@reduxjs/toolkit';
import type { PrefetchOptions } from './module';
import type { UnwrapPromise } from '../tsHelpers';
declare module './module' {
interface ApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> extends Matchers<QueryThunk, Definition> {
}
interface ApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> extends Matchers<MutationThunk, Definition> {
}
}
declare type EndpointThunk<Thunk extends QueryThunk | MutationThunk, Definition extends EndpointDefinition<any, any, any, any>> = Definition extends EndpointDefinition<infer QueryArg, infer BaseQueryFn, any, infer ResultType> ? Thunk extends AsyncThunk<unknown, infer ATArg, infer ATConfig> ? AsyncThunk<ResultType, ATArg & {
originalArgs: QueryArg;
}, ATConfig & {
rejectValue: BaseQueryError<BaseQueryFn>;
}> : never : never;
export declare type PendingAction<Thunk extends QueryThunk | MutationThunk, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>;
export declare type FulfilledAction<Thunk extends QueryThunk | MutationThunk, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>;
export declare type RejectedAction<Thunk extends QueryThunk | MutationThunk, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>;
export declare type Matcher<M> = (value: any) => value is M;
export interface Matchers<Thunk extends QueryThunk | MutationThunk, Definition extends EndpointDefinition<any, any, any, any>> {
matchPending: Matcher<PendingAction<Thunk, Definition>>;
matchFulfilled: Matcher<FulfilledAction<Thunk, Definition>>;
matchRejected: Matcher<RejectedAction<Thunk, Definition>>;
}
export interface QueryThunkArg extends QuerySubstateIdentifier, StartQueryActionCreatorOptions {
type: 'query';
originalArgs: unknown;
endpointName: string;
}
export interface MutationThunkArg {
type: 'mutation';
originalArgs: unknown;
endpointName: string;
track?: boolean;
fixedCacheKey?: string;
}
export declare type ThunkResult = unknown;
export declare type ThunkApiMetaConfig = {
pendingMeta: {
startedTimeStamp: number;
[SHOULD_AUTOBATCH]: true;
};
fulfilledMeta: {
fulfilledTimeStamp: number;
baseQueryMeta: unknown;
[SHOULD_AUTOBATCH]: true;
};
rejectedMeta: {
baseQueryMeta: unknown;
[SHOULD_AUTOBATCH]: true;
};
};
export declare type QueryThunk = AsyncThunk<ThunkResult, QueryThunkArg, ThunkApiMetaConfig>;
export declare type MutationThunk = AsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig>;
export declare type MaybeDrafted<T> = T | Draft<T>;
export declare type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>;
export declare type UpsertRecipe<T> = (data: MaybeDrafted<T> | undefined) => void | MaybeDrafted<T>;
export declare type PatchQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, args: QueryArgFrom<Definitions[EndpointName]>, patches: readonly Patch[], updateProvided?: boolean) => ThunkAction<void, PartialState, any, AnyAction>;
export declare type UpdateQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, args: QueryArgFrom<Definitions[EndpointName]>, updateRecipe: Recipe<ResultTypeFrom<Definitions[EndpointName]>>, updateProvided?: boolean) => ThunkAction<PatchCollection, PartialState, any, AnyAction>;
export declare type UpsertQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, args: QueryArgFrom<Definitions[EndpointName]>, value: ResultTypeFrom<Definitions[EndpointName]>) => ThunkAction<QueryActionCreatorResult<Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? Definitions[EndpointName] : never>, PartialState, any, AnyAction>;
/**
* An object returned from dispatching a `api.util.updateQueryData` call.
*/
export declare type PatchCollection = {
/**
* An `immer` Patch describing the cache update.
*/
patches: Patch[];
/**
* An `immer` Patch to revert the cache update.
*/
inversePatches: Patch[];
/**
* A function that will undo the cache update.
*/
undo: () => void;
};
export declare function buildThunks<BaseQuery extends BaseQueryFn, ReducerPath extends string, Definitions extends EndpointDefinitions>({ reducerPath, baseQuery, context: { endpointDefinitions }, serializeQueryArgs, api, assertTagType, }: {
baseQuery: BaseQuery;
reducerPath: ReducerPath;
context: ApiContext<Definitions>;
serializeQueryArgs: InternalSerializeQueryArgs;
api: Api<BaseQuery, Definitions, ReducerPath, any>;
assertTagType: AssertTagTypes;
}): {
queryThunk: AsyncThunk<unknown, QueryThunkArg, {
pendingMeta: {
startedTimeStamp: number;
RTK_autoBatch: true;
};
fulfilledMeta: {
fulfilledTimeStamp: number;
baseQueryMeta: unknown;
RTK_autoBatch: true;
};
rejectedMeta: {
baseQueryMeta: unknown;
RTK_autoBatch: true;
};
state: RootState<any, string, ReducerPath>;
extra?: unknown;
dispatch?: import("redux").Dispatch<AnyAction> | undefined;
rejectValue?: unknown;
serializedErrorType?: unknown;
}>;
mutationThunk: AsyncThunk<unknown, MutationThunkArg, {
pendingMeta: {
startedTimeStamp: number;
RTK_autoBatch: true;
};
fulfilledMeta: {
fulfilledTimeStamp: number;
baseQueryMeta: unknown;
RTK_autoBatch: true;
};
rejectedMeta: {
baseQueryMeta: unknown;
RTK_autoBatch: true;
};
state: RootState<any, string, ReducerPath>;
extra?: unknown;
dispatch?: import("redux").Dispatch<AnyAction> | undefined;
rejectValue?: unknown;
serializedErrorType?: unknown;
}>;
prefetch: <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: any, options: PrefetchOptions) => ThunkAction<void, any, any, AnyAction>;
updateQueryData: UpdateQueryDataThunk<EndpointDefinitions, { [P in ReducerPath]: import("./apiState").CombinedState<any, string, P>; }>;
upsertQueryData: UpsertQueryDataThunk<Definitions, { [P in ReducerPath]: import("./apiState").CombinedState<any, string, P>; }>;
patchQueryData: PatchQueryDataThunk<EndpointDefinitions, { [P in ReducerPath]: import("./apiState").CombinedState<any, string, P>; }>;
buildMatchThunkActions: <Thunk extends AsyncThunk<any, QueryThunkArg, ThunkApiMetaConfig> | AsyncThunk<any, MutationThunkArg, ThunkApiMetaConfig>>(thunk: Thunk, endpointName: string) => Matchers<Thunk, any>;
};
export declare function calculateProvidedByThunk(action: UnwrapPromise<ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<MutationThunk>>>, type: 'providesTags' | 'invalidatesTags', endpointDefinitions: EndpointDefinitions, assertTagType: AssertTagTypes): readonly FullTagDescription<string>[];
export {};

View File

@@ -0,0 +1,4 @@
import { CreateApi } from '../createApi';
import { coreModule, coreModuleName } from './module';
declare const createApi: CreateApi<typeof coreModuleName>;
export { createApi, coreModule, coreModuleName };

View File

@@ -0,0 +1,334 @@
/**
* Note: this file should import all other files for type discovery and declaration merging
*/
import type { PatchQueryDataThunk, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';
import './buildThunks';
import type { ActionCreatorWithPayload, AnyAction, Middleware, Reducer, ThunkAction, ThunkDispatch } from '@reduxjs/toolkit';
import type { EndpointDefinitions, QueryArgFrom, QueryDefinition, MutationDefinition, TagDescription } from '../endpointDefinitions';
import type { CombinedState, QueryKeys, MutationKeys, RootState } from './apiState';
import type { Module } from '../apiTypes';
import { onFocus, onFocusLost, onOnline, onOffline } from './setupListeners';
import './buildSelectors';
import type { MutationActionCreatorResult, QueryActionCreatorResult } from './buildInitiate';
import './buildInitiate';
import type { SliceActions } from './buildSlice';
import type { BaseQueryFn } from '../baseQueryTypes';
import type { ReferenceCacheLifecycle } from './buildMiddleware/cacheLifecycle';
import type { ReferenceQueryLifecycle } from './buildMiddleware/queryLifecycle';
import type { ReferenceCacheCollection } from './buildMiddleware/cacheCollection';
/**
* `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_
* - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value
*
* @overloadSummary
* `force`
* - If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.
*/
export declare type PrefetchOptions = {
ifOlderThan?: false | number;
} | {
force?: boolean;
};
export declare const coreModuleName: unique symbol;
export declare type CoreModule = typeof coreModuleName | ReferenceCacheLifecycle | ReferenceQueryLifecycle | ReferenceCacheCollection;
export interface ThunkWithReturnValue<T> extends ThunkAction<T, any, any, AnyAction> {
}
declare module '../apiTypes' {
interface ApiModules<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {
[coreModuleName]: {
/**
* This api's reducer should be mounted at `store[api.reducerPath]`.
*
* @example
* ```ts
* configureStore({
* reducer: {
* [api.reducerPath]: api.reducer,
* },
* middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
* })
* ```
*/
reducerPath: ReducerPath;
/**
* Internal actions not part of the public API. Note: These are subject to change at any given time.
*/
internalActions: InternalActions;
/**
* A standard redux reducer that enables core functionality. Make sure it's included in your store.
*
* @example
* ```ts
* configureStore({
* reducer: {
* [api.reducerPath]: api.reducer,
* },
* middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
* })
* ```
*/
reducer: Reducer<CombinedState<Definitions, TagTypes, ReducerPath>, AnyAction>;
/**
* This is a standard redux middleware and is responsible for things like polling, garbage collection and a handful of other things. Make sure it's included in your store.
*
* @example
* ```ts
* configureStore({
* reducer: {
* [api.reducerPath]: api.reducer,
* },
* middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
* })
* ```
*/
middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, AnyAction>>;
/**
* A collection of utility thunks for various situations.
*/
util: {
/**
* This method had to be removed due to a conceptual bug in RTK.
*
* Despite TypeScript errors, it will continue working in the "buggy" way it did
* before in production builds and will be removed in the next major release.
*
* Nonetheless, you should immediately replace it with the new recommended approach.
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for new guidance on SSR.
*
* Please see https://github.com/reduxjs/redux-toolkit/pull/2481 for details.
* @deprecated
*/
getRunningOperationPromises: never;
/**
* This method had to be removed due to a conceptual bug in RTK.
* It has been replaced by `api.util.getRunningQueryThunk` and `api.util.getRunningMutationThunk`.
* Please see https://github.com/reduxjs/redux-toolkit/pull/2481 for details.
* @deprecated
*/
getRunningOperationPromise: never;
/**
* A thunk that (if dispatched) will return a specific running query, identified
* by `endpointName` and `args`.
* If that query is not running, dispatching the thunk will result in `undefined`.
*
* Can be used to await a specific query triggered in any way,
* including via hook calls or manually dispatching `initiate` actions.
*
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
*/
getRunningQueryThunk<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, args: QueryArgFrom<Definitions[EndpointName]>): ThunkWithReturnValue<QueryActionCreatorResult<Definitions[EndpointName] & {
type: 'query';
}> | undefined>;
/**
* A thunk that (if dispatched) will return a specific running mutation, identified
* by `endpointName` and `fixedCacheKey` or `requestId`.
* If that mutation is not running, dispatching the thunk will result in `undefined`.
*
* Can be used to await a specific mutation triggered in any way,
* including via hook trigger functions or manually dispatching `initiate` actions.
*
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
*/
getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(endpointName: EndpointName, fixedCacheKeyOrRequestId: string): ThunkWithReturnValue<MutationActionCreatorResult<Definitions[EndpointName] & {
type: 'mutation';
}> | undefined>;
/**
* A thunk that (if dispatched) will return all running queries.
*
* Useful for SSR scenarios to await all running queries triggered in any way,
* including via hook calls or manually dispatching `initiate` actions.
*
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
*/
getRunningQueriesThunk(): ThunkWithReturnValue<Array<QueryActionCreatorResult<any>>>;
/**
* A thunk that (if dispatched) will return all running mutations.
*
* Useful for SSR scenarios to await all running mutations triggered in any way,
* including via hook calls or manually dispatching `initiate` actions.
*
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
*/
getRunningMutationsThunk(): ThunkWithReturnValue<Array<MutationActionCreatorResult<any>>>;
/**
* A Redux thunk that can be used to manually trigger pre-fetching of data.
*
* The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.
*
* React Hooks users will most likely never need to use this directly, as the `usePrefetch` hook will dispatch this thunk internally as needed when you call the prefetching function supplied by the hook.
*
* @example
*
* ```ts no-transpile
* dispatch(api.util.prefetch('getPosts', undefined, { force: true }))
* ```
*/
prefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, options: PrefetchOptions): ThunkAction<void, any, any, AnyAction>;
/**
* A Redux thunk action creator that, when dispatched, creates and applies a set of JSON diff/patch objects to the current state. This immediately updates the Redux state with those changes.
*
* The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and an `updateRecipe` callback function. The callback receives an Immer-wrapped `draft` of the current state, and may modify the draft to match the expected results after the mutation completes successfully.
*
* The thunk executes _synchronously_, and returns an object containing `{patches: Patch[], inversePatches: Patch[], undo: () => void}`. The `patches` and `inversePatches` are generated using Immer's [`produceWithPatches` method](https://immerjs.github.io/immer/patches).
*
* This is typically used as the first step in implementing optimistic updates. The generated `inversePatches` can be used to revert the updates by calling `dispatch(patchQueryData(endpointName, args, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.
*
* Note that the first two arguments (`endpointName` and `args`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.
*
* @example
*
* ```ts
* const patchCollection = dispatch(
* api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
* draftPosts.push({ id: 1, name: 'Teddy' })
* })
* )
* ```
*/
updateQueryData: UpdateQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
/** @deprecated renamed to `updateQueryData` */
updateQueryResult: UpdateQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
/**
* A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.
*
* The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and the data to upsert.
*
* If no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will _overwrite_ the existing cache entry data.
*
* The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.
*
* If dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a "last result wins" update behavior.
*
* @example
*
* ```ts
* await dispatch(
* api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: "Hello!"})
* )
* ```
*/
upsertQueryData: UpsertQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
/**
* A Redux thunk that applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.
*
* The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.
*
* This is typically used as the second step in implementing optimistic updates. If a request fails, the optimistically-applied changes can be reverted by dispatching `patchQueryData` with the `inversePatches` that were generated by `updateQueryData` earlier.
*
* In cases where it is desired to simply revert the previous changes, it may be preferable to call the `undo` method returned from dispatching `updateQueryData` instead.
*
* @example
* ```ts
* const patchCollection = dispatch(
* api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
* draftPosts.push({ id: 1, name: 'Teddy' })
* })
* )
*
* // later
* dispatch(
* api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)
* )
*
* // or
* patchCollection.undo()
* ```
*/
patchQueryData: PatchQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
/** @deprecated renamed to `patchQueryData` */
patchQueryResult: PatchQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
/**
* A Redux action creator that can be dispatched to manually reset the api state completely. This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'.
*
* @example
*
* ```ts
* dispatch(api.util.resetApiState())
* ```
*/
resetApiState: SliceActions['resetApiState'];
/**
* A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).
*
* The action creator accepts one argument: the cache tags to be invalidated. It returns an action with those tags as a payload, and the corresponding `invalidateTags` action type for the api.
*
* Dispatching the result of this action creator will [invalidate](../../usage/automated-refetching.mdx#invalidating-cache-data) the given tags, causing queries to automatically re-fetch if they are subscribed to cache data that [provides](../../usage/automated-refetching.mdx#providing-cache-data) the corresponding tags.
*
* The array of tags provided to the action creator should be in one of the following formats, where `TagType` is equal to a string provided to the [`tagTypes`](../createApi.mdx#tagtypes) property of the api:
*
* - `[TagType]`
* - `[{ type: TagType }]`
* - `[{ type: TagType, id: number | string }]`
*
* @example
*
* ```ts
* dispatch(api.util.invalidateTags(['Post']))
* dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))
* dispatch(
* api.util.invalidateTags([
* { type: 'Post', id: 1 },
* { type: 'Post', id: 'LIST' },
* ])
* )
* ```
*/
invalidateTags: ActionCreatorWithPayload<Array<TagDescription<TagTypes>>, string>;
/**
* A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.
*
* Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.
*/
selectInvalidatedBy: (state: RootState<Definitions, string, ReducerPath>, tags: ReadonlyArray<TagDescription<TagTypes>>) => Array<{
endpointName: string;
originalArgs: any;
queryCacheKey: string;
}>;
};
/**
* Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.
*/
endpoints: {
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? ApiEndpointQuery<Definitions[K], Definitions> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? ApiEndpointMutation<Definitions[K], Definitions> : never;
};
};
}
}
export interface ApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
name: string;
/**
* All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
*/
Types: NonNullable<Definition['Types']>;
}
export interface ApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
name: string;
/**
* All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
*/
Types: NonNullable<Definition['Types']>;
}
export declare type ListenerActions = {
/**
* Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior
* @link https://rtk-query-docs.netlify.app/api/setupListeners
*/
onOnline: typeof onOnline;
onOffline: typeof onOffline;
/**
* Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior
* @link https://rtk-query-docs.netlify.app/api/setupListeners
*/
onFocus: typeof onFocus;
onFocusLost: typeof onFocusLost;
};
export declare type InternalActions = SliceActions & ListenerActions;
/**
* Creates a module containing the basic redux logic for use with `buildCreateApi`.
*
* @example
* ```ts
* const createBaseApi = buildCreateApi(coreModule());
* ```
*/
export declare const coreModule: () => Module<CoreModule>;

View File

@@ -0,0 +1,27 @@
import type { ThunkDispatch, ActionCreatorWithoutPayload } from '@reduxjs/toolkit';
export declare const onFocus: ActionCreatorWithoutPayload<"__rtkq/focused">;
export declare const onFocusLost: ActionCreatorWithoutPayload<"__rtkq/unfocused">;
export declare const onOnline: ActionCreatorWithoutPayload<"__rtkq/online">;
export declare const onOffline: ActionCreatorWithoutPayload<"__rtkq/offline">;
/**
* A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.
* It requires the dispatch method from your store.
* Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,
* but you have the option of providing a callback for more granular control.
*
* @example
* ```ts
* setupListeners(store.dispatch)
* ```
*
* @param dispatch - The dispatch method from your store
* @param customHandler - An optional callback for more granular control over listener behavior
* @returns Return value of the handler.
* The default handler returns an `unsubscribe` method that can be called to remove the listeners.
*/
export declare function setupListeners(dispatch: ThunkDispatch<any, any, any>, customHandler?: (dispatch: ThunkDispatch<any, any, any>, actions: {
onFocus: typeof onFocus;
onFocusLost: typeof onFocusLost;
onOnline: typeof onOnline;
onOffline: typeof onOffline;
}) => () => void): () => void;

194
node_modules/@reduxjs/toolkit/dist/query/createApi.d.ts generated vendored Normal file
View File

@@ -0,0 +1,194 @@
import type { Api, Module, ModuleName } from './apiTypes';
import type { CombinedState } from './core/apiState';
import type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes';
import type { SerializeQueryArgs } from './defaultSerializeQueryArgs';
import type { EndpointBuilder, EndpointDefinitions } from './endpointDefinitions';
import type { AnyAction } from '@reduxjs/toolkit';
import type { NoInfer } from './tsHelpers';
export interface CreateApiOptions<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never> {
/**
* The base query used by each endpoint if no `queryFn` option is specified. RTK Query exports a utility called [fetchBaseQuery](./fetchBaseQuery) as a lightweight wrapper around `fetch` for common use-cases. See [Customizing Queries](../../rtk-query/usage/customizing-queries) if `fetchBaseQuery` does not handle your requirements.
*
* @example
*
* ```ts
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
*
* const api = createApi({
* // highlight-start
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* // highlight-end
* endpoints: (build) => ({
* // ...endpoints
* }),
* })
* ```
*/
baseQuery: BaseQuery;
/**
* An array of string tag type names. Specifying tag types is optional, but you should define them so that they can be used for caching and invalidation. When defining a tag type, you will be able to [provide](../../rtk-query/usage/automated-refetching#providing-tags) them with `providesTags` and [invalidate](../../rtk-query/usage/automated-refetching#invalidating-tags) them with `invalidatesTags` when configuring [endpoints](#endpoints).
*
* @example
*
* ```ts
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* // highlight-start
* tagTypes: ['Post', 'User'],
* // highlight-end
* endpoints: (build) => ({
* // ...endpoints
* }),
* })
* ```
*/
tagTypes?: readonly TagTypes[];
/**
* The `reducerPath` is a _unique_ key that your service will be mounted to in your store. If you call `createApi` more than once in your application, you will need to provide a unique value each time. Defaults to `'api'`.
*
* @example
*
* ```ts
* // codeblock-meta title="apis.js"
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';
*
* const apiOne = createApi({
* // highlight-start
* reducerPath: 'apiOne',
* // highlight-end
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (builder) => ({
* // ...endpoints
* }),
* });
*
* const apiTwo = createApi({
* // highlight-start
* reducerPath: 'apiTwo',
* // highlight-end
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (builder) => ({
* // ...endpoints
* }),
* });
* ```
*/
reducerPath?: ReducerPath;
/**
* Accepts a custom function if you have a need to change the creation of cache keys for any reason.
*/
serializeQueryArgs?: SerializeQueryArgs<BaseQueryArg<BaseQuery>>;
/**
* Endpoints are just a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are two basic endpoint types: [`query`](../../rtk-query/usage/queries) and [`mutation`](../../rtk-query/usage/mutations).
*/
endpoints(build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>): Definitions;
/**
* Defaults to `60` _(this value is in seconds)_. This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.
*
* ```ts
* // codeblock-meta title="keepUnusedDataFor example"
*
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
* type PostsResponse = Post[]
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (build) => ({
* getPosts: build.query<PostsResponse, void>({
* query: () => 'posts',
* // highlight-start
* keepUnusedDataFor: 5
* // highlight-end
* })
* })
* })
* ```
*/
keepUnusedDataFor?: number;
/**
* 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;
/**
* Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*
* Note: requires [`setupListeners`](./setupListeners) to have been called.
*/
refetchOnFocus?: boolean;
/**
* Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*
* Note: requires [`setupListeners`](./setupListeners) to have been called.
*/
refetchOnReconnect?: boolean;
/**
* A function that is passed every dispatched action. If this returns something other than `undefined`,
* that return value will be used to rehydrate fulfilled & errored queries.
*
* @example
*
* ```ts
* // codeblock-meta title="next-redux-wrapper rehydration example"
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
* import { HYDRATE } from 'next-redux-wrapper'
*
* export const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* // highlight-start
* extractRehydrationInfo(action, { reducerPath }) {
* if (action.type === HYDRATE) {
* return action.payload[reducerPath]
* }
* },
* // highlight-end
* endpoints: (build) => ({
* // omitted
* }),
* })
* ```
*/
extractRehydrationInfo?: (action: AnyAction, { reducerPath, }: {
reducerPath: ReducerPath;
}) => undefined | CombinedState<NoInfer<Definitions>, NoInfer<TagTypes>, NoInfer<ReducerPath>>;
}
export declare type CreateApi<Modules extends ModuleName> = {
/**
* Creates a service to use in your application. Contains only the basic redux logic (the core module).
*
* @link https://rtk-query-docs.netlify.app/api/createApi
*/
<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never>(options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>;
};
/**
* Builds a `createApi` method based on the provided `modules`.
*
* @link https://rtk-query-docs.netlify.app/concepts/customizing-create-api
*
* @example
* ```ts
* const MyContext = React.createContext<ReactReduxContextValue>(null as any);
* const customCreateApi = buildCreateApi(
* coreModule(),
* reactHooksModule({ useDispatch: createDispatchHook(MyContext) })
* );
* ```
*
* @param modules - A variable number of modules that customize how the `createApi` method handles endpoints
* @returns A `createApi` method using the provided `modules`.
*/
export declare function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(...modules: Modules): CreateApi<Modules[number]['name']>;

View File

@@ -0,0 +1,13 @@
import type { QueryCacheKey } from './core/apiState';
import type { EndpointDefinition } from './endpointDefinitions';
export declare const defaultSerializeQueryArgs: SerializeQueryArgs<any>;
export declare type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {
queryArgs: QueryArgs;
endpointDefinition: EndpointDefinition<any, any, any, any>;
endpointName: string;
}) => ReturnType;
export declare type InternalSerializeQueryArgs = (_: {
queryArgs: any;
endpointDefinition: EndpointDefinition<any, any, any, any>;
endpointName: string;
}) => QueryCacheKey;

View File

@@ -0,0 +1,540 @@
import type { AnyAction, ThunkDispatch } from '@reduxjs/toolkit';
import type { SerializeQueryArgs } from './defaultSerializeQueryArgs';
import type { QuerySubState, RootState } from './core/apiState';
import type { BaseQueryExtraOptions, BaseQueryFn, BaseQueryResult, BaseQueryArg, BaseQueryApi, QueryReturnValue, BaseQueryError, BaseQueryMeta } from './baseQueryTypes';
import type { HasRequiredProps, MaybePromise, OmitFromUnion, CastAny, NonUndefined, UnwrapPromise } from './tsHelpers';
import type { NEVER } from './fakeBaseQuery';
import type { Api } from '@reduxjs/toolkit/query';
declare const resultType: unique symbol;
declare const baseQuery: unique symbol;
interface EndpointDefinitionWithQuery<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {
/**
* `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.
*
* @example
*
* ```ts
* // codeblock-meta title="query example"
*
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
* type PostsResponse = Post[]
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* tagTypes: ['Post'],
* endpoints: (build) => ({
* getPosts: build.query<PostsResponse, void>({
* // highlight-start
* query: () => 'posts',
* // highlight-end
* }),
* addPost: build.mutation<Post, Partial<Post>>({
* // highlight-start
* query: (body) => ({
* url: `posts`,
* method: 'POST',
* body,
* }),
* // highlight-end
* invalidatesTags: [{ type: 'Post', id: 'LIST' }],
* }),
* })
* })
* ```
*/
query(arg: QueryArg): BaseQueryArg<BaseQuery>;
queryFn?: never;
/**
* A function to manipulate the data returned by a query or mutation.
*/
transformResponse?(baseQueryReturnValue: BaseQueryResult<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): ResultType | Promise<ResultType>;
/**
* A function to manipulate the data returned by a failed query or mutation.
*/
transformErrorResponse?(baseQueryReturnValue: BaseQueryError<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): unknown;
/**
* Defaults to `true`.
*
* Most apps should leave this setting on. The only time it can be a performance issue
* is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and
* you're unable to paginate it.
*
* For details of how this works, please see the below. When it is set to `false`,
* every request will cause subscribed components to rerender, even when the data has not changed.
*
* @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing
*/
structuralSharing?: boolean;
}
interface EndpointDefinitionWithQueryFn<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {
/**
* Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.
*
* @example
* ```ts
* // codeblock-meta title="Basic queryFn example"
*
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
* type PostsResponse = Post[]
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (build) => ({
* getPosts: build.query<PostsResponse, void>({
* query: () => 'posts',
* }),
* flipCoin: build.query<'heads' | 'tails', void>({
* // highlight-start
* queryFn(arg, queryApi, extraOptions, baseQuery) {
* const randomVal = Math.random()
* if (randomVal < 0.45) {
* return { data: 'heads' }
* }
* if (randomVal < 0.9) {
* return { data: 'tails' }
* }
* return { error: { status: 500, statusText: 'Internal Server Error', data: "Coin landed on it's edge!" } }
* }
* // highlight-end
* })
* })
* })
* ```
*/
queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions<BaseQuery>, baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>>>;
query?: never;
transformResponse?: never;
transformErrorResponse?: never;
/**
* Defaults to `true`.
*
* Most apps should leave this setting on. The only time it can be a performance issue
* is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and
* you're unable to paginate it.
*
* For details of how this works, please see the below. When it is set to `false`,
* every request will cause subscribed components to rerender, even when the data has not changed.
*
* @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing
*/
structuralSharing?: boolean;
}
export interface BaseEndpointTypes<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {
QueryArg: QueryArg;
BaseQuery: BaseQuery;
ResultType: ResultType;
}
export declare type BaseEndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = (([CastAny<BaseQueryResult<BaseQuery>, {}>] extends [NEVER] ? never : EndpointDefinitionWithQuery<QueryArg, BaseQuery, ResultType>) | EndpointDefinitionWithQueryFn<QueryArg, BaseQuery, ResultType>) & {
[resultType]?: ResultType;
[baseQuery]?: BaseQuery;
} & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {
extraOptions: BaseQueryExtraOptions<BaseQuery>;
}, {
extraOptions?: BaseQueryExtraOptions<BaseQuery>;
}>;
export declare enum DefinitionType {
query = "query",
mutation = "mutation"
}
export declare type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => ReadonlyArray<TagDescription<TagTypes>>;
export declare type FullTagDescription<TagType> = {
type: TagType;
id?: number | string;
};
export declare type TagDescription<TagType> = TagType | FullTagDescription<TagType>;
export declare type ResultDescription<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = ReadonlyArray<TagDescription<TagTypes>> | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>;
/** @deprecated please use `onQueryStarted` instead */
export interface QueryApi<ReducerPath extends string, Context extends {}> {
/** @deprecated please use `onQueryStarted` instead */
dispatch: ThunkDispatch<any, any, AnyAction>;
/** @deprecated please use `onQueryStarted` instead */
getState(): RootState<any, any, ReducerPath>;
/** @deprecated please use `onQueryStarted` instead */
extra: unknown;
/** @deprecated please use `onQueryStarted` instead */
requestId: string;
/** @deprecated please use `onQueryStarted` instead */
context: Context;
}
export interface QueryTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> extends BaseEndpointTypes<QueryArg, BaseQuery, ResultType> {
/**
* The endpoint definition type. To be used with some internal generic types.
* @example
* ```ts
* const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...
* ```
*/
QueryDefinition: QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
TagTypes: TagTypes;
ReducerPath: ReducerPath;
}
export interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> {
type: DefinitionType.query;
/**
* Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.
* Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.
* 1. `['Post']` - equivalent to `2`
* 2. `[{ type: 'Post' }]` - equivalent to `1`
* 3. `[{ type: 'Post', id: 1 }]`
* 4. `(result, error, arg) => ['Post']` - equivalent to `5`
* 5. `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`
* 6. `(result, error, arg) => [{ type: 'Post', id: 1 }]`
*
* @example
*
* ```ts
* // codeblock-meta title="providesTags example"
*
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
* type PostsResponse = Post[]
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* tagTypes: ['Posts'],
* endpoints: (build) => ({
* getPosts: build.query<PostsResponse, void>({
* query: () => 'posts',
* // highlight-start
* providesTags: (result) =>
* result
* ? [
* ...result.map(({ id }) => ({ type: 'Posts' as const, id })),
* { type: 'Posts', id: 'LIST' },
* ]
* : [{ type: 'Posts', id: 'LIST' }],
* // highlight-end
* })
* })
* })
* ```
*/
providesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;
/**
* Not to be used. A query should not invalidate tags in the cache.
*/
invalidatesTags?: never;
/**
* Can be provided to return a custom cache key value based on the query arguments.
*
* This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key. It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.
*
* Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean. If it returns a string, that value will be used as the cache key directly. If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`. This simplifies the use case of stripping out args you don't want included in the cache key.
*
*
* @example
*
* ```ts
* // codeblock-meta title="serializeQueryArgs : exclude value"
*
* import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
*
* interface MyApiClient {
* fetchPost: (id: string) => Promise<Post>
* }
*
* createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (build) => ({
* // Example: an endpoint with an API client passed in as an argument,
* // but only the item ID should be used as the cache key
* getPost: build.query<Post, { id: string; client: MyApiClient }>({
* queryFn: async ({ id, client }) => {
* const post = await client.fetchPost(id)
* return { data: post }
* },
* // highlight-start
* serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {
* const { id } = queryArgs
* // This can return a string, an object, a number, or a boolean.
* // If it returns an object, number or boolean, that value
* // will be serialized automatically via `defaultSerializeQueryArgs`
* return { id } // omit `client` from the cache key
*
* // Alternately, you can use `defaultSerializeQueryArgs` yourself:
* // return defaultSerializeQueryArgs({
* // endpointName,
* // queryArgs: { id },
* // endpointDefinition
* // })
* // Or create and return a string yourself:
* // return `getPost(${id})`
* },
* // highlight-end
* }),
* }),
*})
* ```
*/
serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;
/**
* Can be provided to merge an incoming response value into the current cache data.
* If supplied, no automatic structural sharing will be applied - it's up to
* you to update the cache appropriately.
*
* Since RTKQ normally replaces cache entries with the new response, you will usually
* need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep
* an existing cache entry so that it can be updated.
*
* Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,
* or return a new value, but _not_ both at once.
*
* Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,
* the cache entry will just save the response data directly.
*
* Useful if you don't want a new request to completely override the current cache value,
* maybe because you have manually updated it from another source and don't want those
* updates to get lost.
*
*
* @example
*
* ```ts
* // codeblock-meta title="merge: pagination"
*
* import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
*
* createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (build) => ({
* listItems: build.query<string[], number>({
* query: (pageNumber) => `/listItems?page=${pageNumber}`,
* // Only have one cache entry because the arg always maps to one string
* serializeQueryArgs: ({ endpointName }) => {
* return endpointName
* },
* // Always merge incoming data to the cache entry
* merge: (currentCache, newItems) => {
* currentCache.push(...newItems)
* },
* // Refetch when the page arg changes
* forceRefetch({ currentArg, previousArg }) {
* return currentArg !== previousArg
* },
* }),
* }),
*})
* ```
*/
merge?(currentCacheData: ResultType, responseData: ResultType, otherArgs: {
arg: QueryArg;
baseQueryMeta: BaseQueryMeta<BaseQuery>;
requestId: string;
fulfilledTimeStamp: number;
}): ResultType | void;
/**
* Check to see if the endpoint should force a refetch in cases where it normally wouldn't.
* This is primarily useful for "infinite scroll" / pagination use cases where
* RTKQ is keeping a single cache entry that is added to over time, in combination
* with `serializeQueryArgs` returning a fixed cache key and a `merge` callback
* set to add incoming data to the cache entry each time.
*
* @example
*
* ```ts
* // codeblock-meta title="forceRefresh: pagination"
*
* import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
*
* createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (build) => ({
* listItems: build.query<string[], number>({
* query: (pageNumber) => `/listItems?page=${pageNumber}`,
* // Only have one cache entry because the arg always maps to one string
* serializeQueryArgs: ({ endpointName }) => {
* return endpointName
* },
* // Always merge incoming data to the cache entry
* merge: (currentCache, newItems) => {
* currentCache.push(...newItems)
* },
* // Refetch when the page arg changes
* forceRefetch({ currentArg, previousArg }) {
* return currentArg !== previousArg
* },
* }),
* }),
*})
* ```
*/
forceRefetch?(params: {
currentArg: QueryArg | undefined;
previousArg: QueryArg | undefined;
state: RootState<any, any, string>;
endpointState?: QuerySubState<any>;
}): boolean;
/**
* All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
*/
Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
}
export declare type QueryDefinition<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> & QueryExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>;
export interface MutationTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> extends BaseEndpointTypes<QueryArg, BaseQuery, ResultType> {
/**
* The endpoint definition type. To be used with some internal generic types.
* @example
* ```ts
* const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...
* ```
*/
MutationDefinition: MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
TagTypes: TagTypes;
ReducerPath: ReducerPath;
}
export interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> {
type: DefinitionType.mutation;
/**
* Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.
* Expects the same shapes as `providesTags`.
*
* @example
*
* ```ts
* // codeblock-meta title="invalidatesTags example"
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
* type PostsResponse = Post[]
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* tagTypes: ['Posts'],
* endpoints: (build) => ({
* getPosts: build.query<PostsResponse, void>({
* query: () => 'posts',
* providesTags: (result) =>
* result
* ? [
* ...result.map(({ id }) => ({ type: 'Posts' as const, id })),
* { type: 'Posts', id: 'LIST' },
* ]
* : [{ type: 'Posts', id: 'LIST' }],
* }),
* addPost: build.mutation<Post, Partial<Post>>({
* query(body) {
* return {
* url: `posts`,
* method: 'POST',
* body,
* }
* },
* // highlight-start
* invalidatesTags: [{ type: 'Posts', id: 'LIST' }],
* // highlight-end
* }),
* })
* })
* ```
*/
invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;
/**
* Not to be used. A mutation should not provide tags to the cache.
*/
providesTags?: never;
/**
* All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
*/
Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
}
export declare type MutationDefinition<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> & MutationExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>;
export declare type EndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath> | MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
export declare type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any>>;
export declare function isQueryDefinition(e: EndpointDefinition<any, any, any, any>): e is QueryDefinition<any, any, any, any>;
export declare function isMutationDefinition(e: EndpointDefinition<any, any, any, any>): e is MutationDefinition<any, any, any, any>;
export declare type EndpointBuilder<BaseQuery extends BaseQueryFn, TagTypes extends string, ReducerPath extends string> = {
/**
* An endpoint definition that retrieves data, and may provide tags to the cache.
*
* @example
* ```js
* // codeblock-meta title="Example of all query endpoint options"
* const api = createApi({
* baseQuery,
* endpoints: (build) => ({
* getPost: build.query({
* query: (id) => ({ url: `post/${id}` }),
* // Pick out data and prevent nested properties in a hook or selector
* transformResponse: (response) => response.data,
* // Pick out error and prevent nested properties in a hook or selector
* transformErrorResponse: (response) => response.error,
* // `result` is the server response
* providesTags: (result, error, id) => [{ type: 'Post', id }],
* // trigger side effects or optimistic updates
* onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},
* // handle subscriptions etc
* onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},
* }),
* }),
*});
*```
*/
query<ResultType, QueryArg>(definition: OmitFromUnion<QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>, 'type'>): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
/**
* An endpoint definition that alters data on the server or will possibly invalidate the cache.
*
* @example
* ```js
* // codeblock-meta title="Example of all mutation endpoint options"
* const api = createApi({
* baseQuery,
* endpoints: (build) => ({
* updatePost: build.mutation({
* query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),
* // Pick out data and prevent nested properties in a hook or selector
* transformResponse: (response) => response.data,
* // Pick out error and prevent nested properties in a hook or selector
* transformErrorResponse: (response) => response.error,
* // `result` is the server response
* invalidatesTags: (result, error, id) => [{ type: 'Post', id }],
* // trigger side effects or optimistic updates
* onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},
* // handle subscriptions etc
* onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},
* }),
* }),
* });
* ```
*/
mutation<ResultType, QueryArg>(definition: OmitFromUnion<MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>, 'type'>): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
};
export declare type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;
export declare function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(description: ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType> | undefined, result: ResultType | undefined, error: ErrorType | undefined, queryArg: QueryArg, meta: MetaType | undefined, assertTagTypes: AssertTagTypes): readonly FullTagDescription<string>[];
export declare function expandTagDescription(description: TagDescription<string>): FullTagDescription<string>;
export declare type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any> ? QA : unknown;
export declare type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT> ? RT : unknown;
export declare type ReducerPathFrom<D extends EndpointDefinition<any, any, any, any, any>> = D extends EndpointDefinition<any, any, any, any, infer RP> ? RP : unknown;
export declare type TagTypesFrom<D extends EndpointDefinition<any, any, any, any>> = D extends EndpointDefinition<any, any, infer RP, any> ? RP : unknown;
export declare type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes> ? TagTypes : never;
export declare type DefinitionsFromApi<T> = T extends Api<any, infer Definitions, any, any> ? Definitions : never;
export declare type TransformedResponse<NewDefinitions extends EndpointDefinitions, K, ResultType> = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType : UnwrapPromise<ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>> : ResultType;
export declare type OverrideResultType<Definition, NewResultType> = Definition extends QueryDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends MutationDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : never;
export declare type UpdateDefinitions<Definitions extends EndpointDefinitions, NewTagTypes extends string, NewDefinitions extends EndpointDefinitions> = {
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends MutationDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : never;
};
export {};

View File

@@ -0,0 +1,9 @@
import type { BaseQueryFn } from './baseQueryTypes';
declare const _NEVER: unique symbol;
export declare type NEVER = typeof _NEVER;
/**
* Creates a "fake" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.
* This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.
*/
export declare function fakeBaseQuery<ErrorType>(): BaseQueryFn<void, NEVER, ErrorType, {}>;
export {};

View File

@@ -0,0 +1,135 @@
import type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes';
import type { MaybePromise, Override } from './tsHelpers';
export declare type ResponseHandler = 'content-type' | 'json' | 'text' | ((response: Response) => Promise<any>);
declare type CustomRequestInit = Override<RequestInit, {
headers?: Headers | string[][] | Record<string, string | undefined> | undefined;
}>;
export interface FetchArgs extends CustomRequestInit {
url: string;
params?: Record<string, any>;
body?: any;
responseHandler?: ResponseHandler;
validateStatus?: (response: Response, body: any) => boolean;
/**
* A number in milliseconds that represents that maximum time a request can take before timing out.
*/
timeout?: number;
}
export declare type FetchBaseQueryError = {
/**
* * `number`:
* HTTP status code
*/
status: number;
data: unknown;
} | {
/**
* * `"FETCH_ERROR"`:
* An error that occurred during execution of `fetch` or the `fetchFn` callback option
**/
status: 'FETCH_ERROR';
data?: undefined;
error: string;
} | {
/**
* * `"PARSING_ERROR"`:
* An error happened during parsing.
* Most likely a non-JSON-response was returned with the default `responseHandler` "JSON",
* or an error occurred while executing a custom `responseHandler`.
**/
status: 'PARSING_ERROR';
originalStatus: number;
data: string;
error: string;
} | {
/**
* * `"TIMEOUT_ERROR"`:
* Request timed out
**/
status: 'TIMEOUT_ERROR';
data?: undefined;
error: string;
} | {
/**
* * `"CUSTOM_ERROR"`:
* A custom error type that you can return from your `queryFn` where another error might not make sense.
**/
status: 'CUSTOM_ERROR';
data?: unknown;
error: string;
};
export declare type FetchBaseQueryArgs = {
baseUrl?: string;
prepareHeaders?: (headers: Headers, api: Pick<BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type' | 'forced'>) => MaybePromise<Headers | void>;
fetchFn?: (input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>;
paramsSerializer?: (params: Record<string, any>) => string;
/**
* By default, we only check for 'application/json' and 'application/vnd.api+json' as the content-types for json. If you need to support another format, you can pass
* in a predicate function for your given api to get the same automatic stringifying behavior
* @example
* ```ts
* const isJsonContentType = (headers: Headers) => ["application/vnd.api+json", "application/json", "application/vnd.hal+json"].includes(headers.get("content-type")?.trim());
* ```
*/
isJsonContentType?: (headers: Headers) => boolean;
/**
* Defaults to `application/json`;
*/
jsonContentType?: string;
/**
* Custom replacer function used when calling `JSON.stringify()`;
*/
jsonReplacer?: (this: any, key: string, value: any) => any;
} & RequestInit & Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'>;
export declare type FetchBaseQueryMeta = {
request: Request;
response?: Response;
};
/**
* This is a very small wrapper around fetch that aims to simplify requests.
*
* @example
* ```ts
* const baseQuery = fetchBaseQuery({
* baseUrl: 'https://api.your-really-great-app.com/v1/',
* prepareHeaders: (headers, { getState }) => {
* const token = (getState() as RootState).auth.token;
* // If we have a token set in state, let's assume that we should be passing it.
* if (token) {
* headers.set('authorization', `Bearer ${token}`);
* }
* return headers;
* },
* })
* ```
*
* @param {string} baseUrl
* The base URL for an API service.
* Typically in the format of https://example.com/
*
* @param {(headers: Headers, api: { getState: () => unknown; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders
* An optional function that can be used to inject headers on requests.
* Provides a Headers object, as well as most of the `BaseQueryApi` (`dispatch` is not available).
* Useful for setting authentication or headers that need to be set conditionally.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/Headers
*
* @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn
* Accepts a custom `fetch` function if you do not want to use the default on the window.
* Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`
*
* @param {(params: Record<string, unknown>) => string} paramsSerializer
* An optional function that can be used to stringify querystring parameters.
*
* @param {(headers: Headers) => boolean} isJsonContentType
* An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`
*
* @param {string} jsonContentType Used when automatically setting the content-type header for a request with a jsonifiable body that does not have an explicit content-type header. Defaults to `application/json`.
*
* @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`.
*
* @param {number} timeout
* A number in milliseconds that represents the maximum time a request can take before timing out.
*/
export declare function fetchBaseQuery({ baseUrl, prepareHeaders, fetchFn, paramsSerializer, isJsonContentType, jsonContentType, jsonReplacer, timeout: defaultTimeout, responseHandler: globalResponseHandler, validateStatus: globalValidateStatus, ...baseFetchOptions }?: FetchBaseQueryArgs): BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;
export {};

21
node_modules/@reduxjs/toolkit/dist/query/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,21 @@
export type { CombinedState, QueryCacheKey, QueryKeys, QuerySubState, RootState, SubscriptionOptions, } from './core/apiState';
export { QueryStatus } from './core/apiState';
export type { Api, ApiContext, ApiModules, Module } from './apiTypes';
export type { BaseQueryApi, BaseQueryEnhancer, BaseQueryFn, } from './baseQueryTypes';
export type { EndpointDefinitions, EndpointDefinition, QueryDefinition, MutationDefinition, TagDescription, QueryArgFrom, ResultTypeFrom, DefinitionType, } from './endpointDefinitions';
export { fetchBaseQuery } from './fetchBaseQuery';
export type { FetchBaseQueryError, FetchBaseQueryMeta, FetchArgs, } from './fetchBaseQuery';
export { retry } from './retry';
export { setupListeners } from './core/setupListeners';
export { skipSelector, skipToken } from './core/buildSelectors';
export type { QueryResultSelectorResult, MutationResultSelectorResult, SkipToken, } from './core/buildSelectors';
export type { QueryActionCreatorResult, MutationActionCreatorResult, } from './core/buildInitiate';
export type { CreateApi, CreateApiOptions } from './createApi';
export { buildCreateApi } from './createApi';
export { fakeBaseQuery } from './fakeBaseQuery';
export { copyWithStructuralSharing } from './utils/copyWithStructuralSharing';
export { createApi, coreModule, coreModuleName } from './core';
export type { ApiEndpointMutation, ApiEndpointQuery, CoreModule, PrefetchOptions, } from './core/module';
export { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs';
export type { SerializeQueryArgs } from './defaultSerializeQueryArgs';
export type { Id as TSHelpersId, NoInfer as TSHelpersNoInfer, Override as TSHelpersOverride, } from './tsHelpers';

6
node_modules/@reduxjs/toolkit/dist/query/index.js generated vendored Normal file
View File

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

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/query';
/**
* Can be used as a `Provider` if you **do not already have a Redux store**.
*
* @example
* ```tsx
* // codeblock-meta no-transpile title="Basic usage - wrap your App with ApiProvider"
* import * as React from 'react';
* import { ApiProvider } from '@reduxjs/toolkit/query/react';
* import { Pokemon } from './features/Pokemon';
*
* function App() {
* return (
* <ApiProvider api={api}>
* <Pokemon />
* </ApiProvider>
* );
* }
* ```
*
* @remarks
* Using this together with an existing redux store, both will
* conflict with each other - please use the traditional redux setup
* in that case.
*/
export declare function ApiProvider<A extends Api<any, {}, any, any>>(props: {
children: any;
api: A;
setupListeners?: Parameters<typeof setupListeners>[1] | false;
context?: Context<ReactReduxContextValue>;
}): JSX.Element;

View File

@@ -0,0 +1,375 @@
import { useEffect } from 'react';
import { QueryStatus } from '@reduxjs/toolkit/query';
import type { QuerySubState, SubscriptionOptions, QueryKeys } from '@reduxjs/toolkit/query';
import type { EndpointDefinitions, MutationDefinition, QueryDefinition, QueryArgFrom, ResultTypeFrom } from '@reduxjs/toolkit/query';
import type { MutationResultSelectorResult, SkipToken } from '@reduxjs/toolkit/query';
import type { QueryActionCreatorResult, MutationActionCreatorResult } from '@reduxjs/toolkit/query';
import type { SerializeQueryArgs } from '@reduxjs/toolkit/query';
import type { Api, ApiContext } from '@reduxjs/toolkit/query';
import type { TSHelpersId, TSHelpersNoInfer, TSHelpersOverride } from '@reduxjs/toolkit/query';
import type { CoreModule, PrefetchOptions } from '@reduxjs/toolkit/query';
import type { ReactHooksModuleOptions } from './module';
import type { UninitializedValue } from './constants';
import type { BaseQueryFn } from '../baseQueryTypes';
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>) => UseQueryHookResult<D, R>;
export declare type UseQueryHookResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & UseQuerySubscriptionResult<D>;
/**
* Helper type to manually type the result
* of the `useQuery` hook in userland code.
*/
export declare type TypedUseQueryHookResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> & TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>;
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 the initial load, the cached result will be used
* - **If the query does not have cached data:**
* * The query will have a status of `uninitialized`
* * The query will not exist in the state when viewed with the dev tools
* * The query will not automatically fetch on mount
* * The query will not automatically run when additional components with the same query are added that do run
*
* @example
* ```tsx
* // codeblock-meta no-transpile title="Skip example"
* const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
* const { data, error, status } = useGetPokemonByNameQuery(name, {
* skip,
* });
*
* return (
* <div>
* {name} - {status}
* </div>
* );
* };
* ```
*/
skip?: boolean;
/**
* Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.
* - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
* - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.
* - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*/
refetchOnMountOrArgChange?: boolean | number;
}
/**
* A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.
*
* The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.
*
* Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).
*
* #### Features
*
* - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
*/
export declare type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions) => UseQuerySubscriptionResult<D>;
export declare type UseQuerySubscriptionResult<D extends QueryDefinition<any, any, any, any>> = Pick<QueryActionCreatorResult<D>, 'refetch'>;
/**
* Helper type to manually type the result
* of the `useQuerySubscription` hook in userland code.
*/
export declare type TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscriptionResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
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
*
* #### Note
*
* When the trigger function returned from a LazyQuery is called, it always initiates a new request to the server even if there is cached data. Set `preferCacheValue`(the second argument to the function) as `true` if you want it to immediately return a cached value if one exists.
*/
export declare type UseLazyQuery<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(options?: SubscriptionOptions & Omit<UseQueryStateOptions<D, R>, 'skip'>) => [
LazyQueryTrigger<D>,
UseQueryStateResult<D, R>,
UseLazyQueryLastPromiseInfo<D>
];
export declare type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {
/**
* Triggers a lazy query.
*
* By default, this will start a new request even if there is already a value in the cache.
* If you want to use the cache value and only start a request if there is no cache value, set the second argument to `true`.
*
* @remarks
* If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap with async await"
* try {
* const payload = await getUserById(1).unwrap();
* console.log('fulfilled', payload)
* } catch (error) {
* console.error('rejected', error);
* }
* ```
*/
(arg: QueryArgFrom<D>, preferCacheValue?: boolean): QueryActionCreatorResult<D>;
};
/**
* 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) => readonly [LazyQueryTrigger<D>, 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 extends Record<string, any> = 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> = TSHelpersNoInfer<R>;
/**
* Helper type to manually type the result
* of the `useQueryState` hook in userland code.
*/
export declare type TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TSHelpersNoInfer<R>;
declare type UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> = QuerySubState<D> & {
/**
* Where `data` tries to hold data as much as possible, also re-using
* data from the last arguments passed into the hook, this property
* will always contain the received data from the query, for the current query arguments.
*/
currentData?: ResultTypeFrom<D>;
/**
* Query has not started yet.
*/
isUninitialized: false;
/**
* Query is currently loading for the first time. No data yet.
*/
isLoading: false;
/**
* Query is currently fetching, but might have data from an earlier request.
*/
isFetching: false;
/**
* Query has data from a successful load.
*/
isSuccess: false;
/**
* Query is currently in "error" state.
*/
isError: false;
};
declare type UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> = TSHelpersId<TSHelpersOverride<Extract<UseQueryStateBaseResult<D>, {
status: QueryStatus.uninitialized;
}>, {
isUninitialized: true;
}> | TSHelpersOverride<UseQueryStateBaseResult<D>, {
isLoading: true;
isFetching: boolean;
data: undefined;
} | ({
isSuccess: true;
isFetching: true;
error: undefined;
} & Required<Pick<UseQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp'>>) | ({
isSuccess: true;
isFetching: false;
error: undefined;
} & Required<Pick<UseQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp' | 'currentData'>>) | ({
isError: true;
} & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>)>> & {
/**
* @deprecated 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>;
fixedCacheKey?: string;
};
export declare type UseMutationStateResult<D extends MutationDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R> & {
originalArgs?: QueryArgFrom<D>;
/**
* Resets the hook state to it's initial `uninitialized` state.
* This will also remove the last result from the cache.
*/
reset: () => void;
};
/**
* Helper type to manually type the result
* of the `useMutation` hook in userland code.
*/
export declare type TypedUseMutationResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = MutationResultSelectorResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseMutationStateResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;
/**
* A React hook that lets you trigger an update request for a given endpoint, and subscribes the component to read the request status from the Redux store. The component will re-render as the loading status changes.
*
* #### Features
*
* - Manual control over firing a request to alter data on the server or possibly invalidate the cache
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
export declare type UseMutation<D extends MutationDefinition<any, any, any, any>> = <R extends Record<string, any> = MutationResultSelectorResult<D>>(options?: UseMutationStateOptions<D, R>) => readonly [MutationTrigger<D>, UseMutationStateResult<D, R>];
export declare type MutationTrigger<D extends MutationDefinition<any, any, any, any>> = {
/**
* Triggers the mutation and returns a Promise.
* @remarks
* If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap with async await"
* try {
* const payload = await addPost({ id: 1, name: 'Example' }).unwrap();
* console.log('fulfilled', payload)
* } catch (error) {
* console.error('rejected', error);
* }
* ```
*/
(arg: QueryArgFrom<D>): MutationActionCreatorResult<D>;
};
/**
*
* @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, unstable__sideEffectsInRender, }, serializeQueryArgs, context, }: {
api: Api<any, Definitions, any, any, CoreModule>;
moduleOptions: Required<ReactHooksModuleOptions>;
serializeQueryArgs: SerializeQueryArgs<any>;
context: ApiContext<Definitions>;
}): {
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 { reactHooksModule, reactHooksModuleName } from './module';
export * from '@reduxjs/toolkit/query';
export { ApiProvider } from './ApiProvider';
declare const createApi: import("@reduxjs/toolkit/query").CreateApi<typeof import("@reduxjs/toolkit/query").coreModuleName | typeof reactHooksModuleName>;
export type { TypedUseQueryHookResult, TypedUseQueryStateResult, TypedUseQuerySubscriptionResult, TypedUseMutationResult, } from './buildHooks';
export { createApi, reactHooksModule, reactHooksModuleName };

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,79 @@
import type { MutationHooks, QueryHooks } from './buildHooks';
import type { EndpointDefinitions, QueryDefinition, MutationDefinition, QueryArgFrom } from '@reduxjs/toolkit/query';
import type { Module } from '../apiTypes';
import type { BaseQueryFn } from '@reduxjs/toolkit/query';
import type { HooksWithUniqueNames } from './namedHooks';
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/query' {
interface ApiModules<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {
[reactHooksModuleName]: {
/**
* Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.
*/
endpoints: {
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? QueryHooks<Definitions[K]> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? MutationHooks<Definitions[K]> : never;
};
/**
* A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.
*/
usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, options?: PrefetchOptions): (arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions) => void;
} & HooksWithUniqueNames<Definitions>;
}
}
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'];
/**
* Enables performing asynchronous tasks immediately within a render.
*
* @example
*
* ```ts
* import {
* buildCreateApi,
* coreModule,
* reactHooksModule
* } from '@reduxjs/toolkit/query/react'
*
* const createApi = buildCreateApi(
* coreModule(),
* reactHooksModule({ unstable__sideEffectsInRender: true })
* )
* ```
*/
unstable__sideEffectsInRender?: boolean;
}
/**
* 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, unstable__sideEffectsInRender, }?: ReactHooksModuleOptions) => Module<ReactHooksModule>;
export {};

View File

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

View File

@@ -0,0 +1,491 @@
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; },
reactHooksModuleName: function () { return reactHooksModuleName; }
});
var import_query3 = __toModule(require("@reduxjs/toolkit/query"));
// src/query/react/buildHooks.ts
var import_toolkit2 = __toModule(require("@reduxjs/toolkit"));
var import_react3 = __toModule(require("react"));
var import_query = __toModule(require("@reduxjs/toolkit/query"));
var import_react_redux2 = __toModule(require("react-redux"));
// src/query/react/useSerializedStableValue.ts
var import_react = __toModule(require("react"));
function useStableQueryArgs(queryArgs, serialize, endpointDefinition, endpointName) {
var incoming = (0, import_react.useMemo)(function () { return ({
queryArgs: queryArgs,
serialized: typeof queryArgs == "object" ? serialize({ queryArgs: queryArgs, endpointDefinition: endpointDefinition, endpointName: endpointName }) : queryArgs
}); }, [queryArgs, serialize, endpointDefinition, endpointName]);
var cache2 = (0, import_react.useRef)(incoming);
(0, import_react.useEffect)(function () {
if (cache2.current.serialized !== incoming.serialized) {
cache2.current = incoming;
}
}, [incoming]);
return cache2.current.serialized === incoming.serialized ? cache2.current.queryArgs : queryArgs;
}
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/useShallowStableValue.ts
var import_react2 = __toModule(require("react"));
var import_react_redux = __toModule(require("react-redux"));
function useShallowStableValue(value) {
var cache2 = (0, import_react2.useRef)(value);
(0, import_react2.useEffect)(function () {
if (!(0, import_react_redux.shallowEqual)(cache2.current, value)) {
cache2.current = value;
}
}, [value]);
return (0, import_react_redux.shallowEqual)(cache2.current, value) ? cache2.current : value;
}
// src/query/defaultSerializeQueryArgs.ts
var import_toolkit = __toModule(require("@reduxjs/toolkit"));
var cache = WeakMap ? new WeakMap() : void 0;
var defaultSerializeQueryArgs = function (_c) {
var endpointName = _c.endpointName, queryArgs = _c.queryArgs;
var serialized = "";
var cached = cache == null ? void 0 : cache.get(queryArgs);
if (typeof cached === "string") {
serialized = cached;
}
else {
var stringified = JSON.stringify(queryArgs, function (key, value) { return (0, import_toolkit.isPlainObject)(value) ? Object.keys(value).sort().reduce(function (acc, key2) {
acc[key2] = value[key2];
return acc;
}, {}) : value; });
if ((0, import_toolkit.isPlainObject)(queryArgs)) {
cache == null ? void 0 : cache.set(queryArgs, stringified);
}
serialized = stringified;
}
return endpointName + "(" + serialized + ")";
};
// src/query/react/buildHooks.ts
var useIsomorphicLayoutEffect = typeof window !== "undefined" && !!window.document && !!window.document.createElement ? import_react3.useLayoutEffect : import_react3.useEffect;
var defaultMutationStateSelector = function (x) { return x; };
var noPendingQueryStateSelector = function (selected) {
if (selected.isUninitialized) {
return __spreadProps(__spreadValues({}, selected), {
isUninitialized: false,
isFetching: true,
isLoading: selected.data !== void 0 ? false : 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, unstable__sideEffectsInRender = _d.unstable__sideEffectsInRender, serializeQueryArgs = _c.serializeQueryArgs, context = _c.context;
var usePossiblyImmediateEffect = unstable__sideEffectsInRender ? function (cb) { return cb(); } : import_react3.useEffect;
return { buildQueryHooks: buildQueryHooks, buildMutationHook: buildMutationHook, usePrefetch: usePrefetch };
function queryStatePreSelector(currentState, lastResult, queryArgs) {
if ((lastResult == null ? void 0 : lastResult.endpointName) && currentState.isUninitialized) {
var endpointName = lastResult.endpointName;
var endpointDefinition = context.endpointDefinitions[endpointName];
if (serializeQueryArgs({
queryArgs: lastResult.originalArgs,
endpointDefinition: endpointDefinition,
endpointName: endpointName
}) === serializeQueryArgs({
queryArgs: queryArgs,
endpointDefinition: endpointDefinition,
endpointName: endpointName
}))
lastResult = void 0;
}
var data = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data;
if (data === void 0)
data = currentState.data;
var hasData = data !== void 0;
var isFetching = currentState.isLoading;
var isLoading = !hasData && isFetching;
var isSuccess = currentState.isSuccess || isFetching && hasData;
return __spreadProps(__spreadValues({}, currentState), {
data: data,
currentData: currentState.data,
isFetching: isFetching,
isLoading: isLoading,
isSuccess: isSuccess
});
}
function usePrefetch(endpointName, defaultOptions) {
var dispatch = useDispatch();
var stableDefaultOptions = useShallowStableValue(defaultOptions);
return (0, import_react3.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 = useStableQueryArgs(skip ? import_query.skipToken : arg, defaultSerializeQueryArgs, context.endpointDefinitions[name], name);
var stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect: refetchOnReconnect,
refetchOnFocus: refetchOnFocus,
pollingInterval: pollingInterval
});
var lastRenderHadSubscription = (0, import_react3.useRef)(false);
var promiseRef = (0, import_react3.useRef)();
var _g = promiseRef.current || {}, queryCacheKey = _g.queryCacheKey, requestId = _g.requestId;
var currentRenderHasSubscription = false;
if (queryCacheKey && requestId) {
var returnedValue = dispatch(api.internalActions.internal_probeSubscription({
queryCacheKey: queryCacheKey,
requestId: requestId
}));
if (true) {
if (typeof returnedValue !== "boolean") {
throw new Error("Warning: Middleware for RTK-Query API at reducerPath \"" + api.reducerPath + "\" has not been added to the store.\n You must add the middleware for RTK-Query to function correctly!");
}
}
currentRenderHasSubscription = !!returnedValue;
}
var subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;
usePossiblyImmediateEffect(function () {
lastRenderHadSubscription.current = currentRenderHasSubscription;
});
usePossiblyImmediateEffect(function () {
if (subscriptionRemoved) {
promiseRef.current = void 0;
}
}, [subscriptionRemoved]);
usePossiblyImmediateEffect(function () {
var _a;
var lastPromise = promiseRef.current;
if (typeof process !== "undefined" && false) {
console.log(subscriptionRemoved);
}
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,
subscriptionRemoved
]);
(0, import_react3.useEffect)(function () {
return function () {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return (0, import_react3.useMemo)(function () { return ({
refetch: function () {
var _a;
if (!promiseRef.current)
throw new Error("Cannot refetch a query that has not been started yet.");
return (_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_react3.useState)(UNINITIALIZED_VALUE), arg = _f[0], setArg = _f[1];
var promiseRef = (0, import_react3.useRef)();
var stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect: refetchOnReconnect,
refetchOnFocus: refetchOnFocus,
pollingInterval: pollingInterval
});
usePossiblyImmediateEffect(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_react3.useRef)(stableSubscriptionOptions);
usePossiblyImmediateEffect(function () {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
var trigger = (0, import_react3.useCallback)(function (arg2, preferCacheValue) {
if (preferCacheValue === void 0) { preferCacheValue = false; }
var promise;
batch(function () {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = promise = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
return promise;
}, [dispatch, initiate]);
(0, import_react3.useEffect)(function () {
return function () {
var _a;
(_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
};
}, []);
(0, import_react3.useEffect)(function () {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return (0, import_react3.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, selectFromResult = _d.selectFromResult;
var select = api.endpoints[name].select;
var stableArg = useStableQueryArgs(skip ? import_query.skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);
var lastValue = (0, import_react3.useRef)();
var selectDefaultResult = (0, import_react3.useMemo)(function () { return (0, import_toolkit2.createSelector)([
select(stableArg),
function (_, lastResult) { return lastResult; },
function (_) { return stableArg; }
], queryStatePreSelector); }, [select, stableArg]);
var querySelector = (0, import_react3.useMemo)(function () { return selectFromResult ? (0, import_toolkit2.createSelector)([selectDefaultResult], selectFromResult) : selectDefaultResult; }, [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_react3.useMemo)(function () { return ({ lastArg: arg }); }, [arg]);
return (0, import_react3.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));
var data = queryStateResults.data, status = queryStateResults.status, isLoading = queryStateResults.isLoading, isSuccess = queryStateResults.isSuccess, isError = queryStateResults.isError, error = queryStateResults.error;
(0, import_react3.useDebugValue)({ data: data, status: status, isLoading: isLoading, isSuccess: isSuccess, isError: isError, error: error });
return (0, import_react3.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, fixedCacheKey = _d.fixedCacheKey;
var _f = api.endpoints[name], select = _f.select, initiate = _f.initiate;
var dispatch = useDispatch();
var _g = (0, import_react3.useState)(), promise = _g[0], setPromise = _g[1];
(0, import_react3.useEffect)(function () { return function () {
if (!(promise == null ? void 0 : promise.arg.fixedCacheKey)) {
promise == null ? void 0 : promise.reset();
}
}; }, [promise]);
var triggerMutation = (0, import_react3.useCallback)(function (arg) {
var promise2 = dispatch(initiate(arg, { fixedCacheKey: fixedCacheKey }));
setPromise(promise2);
return promise2;
}, [dispatch, initiate, fixedCacheKey]);
var requestId = (promise || {}).requestId;
var mutationSelector = (0, import_react3.useMemo)(function () { return (0, import_toolkit2.createSelector)([select({ fixedCacheKey: fixedCacheKey, requestId: promise == null ? void 0 : promise.requestId })], selectFromResult); }, [select, promise, selectFromResult, fixedCacheKey]);
var currentState = useSelector(mutationSelector, import_react_redux2.shallowEqual);
var originalArgs = fixedCacheKey == null ? promise == null ? void 0 : promise.arg.originalArgs : void 0;
var reset = (0, import_react3.useCallback)(function () {
batch(function () {
if (promise) {
setPromise(void 0);
}
if (fixedCacheKey) {
dispatch(api.internalActions.removeMutationResult({
requestId: requestId,
fixedCacheKey: fixedCacheKey
}));
}
});
}, [dispatch, fixedCacheKey, promise, requestId]);
var endpointName = currentState.endpointName, data = currentState.data, status = currentState.status, isLoading = currentState.isLoading, isSuccess = currentState.isSuccess, isError = currentState.isError, error = currentState.error;
(0, import_react3.useDebugValue)({
endpointName: endpointName,
data: data,
status: status,
isLoading: isLoading,
isSuccess: isSuccess,
isError: isError,
error: error
});
var finalState = (0, import_react3.useMemo)(function () { return __spreadProps(__spreadValues({}, currentState), { originalArgs: originalArgs, reset: reset }); }, [currentState, originalArgs, reset]);
return (0, import_react3.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, _j = _d.unstable__sideEffectsInRender, unstable__sideEffectsInRender = _j === void 0 ? false : _j;
return ({
name: reactHooksModuleName,
init: function (api, _c, context) {
var serializeQueryArgs = _c.serializeQueryArgs;
var anyApi = api;
var _d = buildHooks({
api: api,
moduleOptions: {
batch: batch,
useDispatch: useDispatch,
useSelector: useSelector,
useStore: useStore,
unstable__sideEffectsInRender: unstable__sideEffectsInRender
},
serializeQueryArgs: serializeQueryArgs,
context: context
}), buildQueryHooks = _d.buildQueryHooks, buildMutationHook = _d.buildMutationHook, usePrefetch = _d.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_toolkit3 = __toModule(require("@reduxjs/toolkit"));
var import_react4 = __toModule(require("react"));
var import_react5 = __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_react5.default.useState(function () {
var _c;
return (0, import_toolkit3.configureStore)({
reducer: (_c = {},
_c[props.api.reducerPath] = props.api.reducer,
_c),
middleware: function (gDM) { return gDM().concat(props.api.middleware); }
});
})[0];
(0, import_react4.useEffect)(function () { return props.setupListeners === false ? void 0 : (0, import_query2.setupListeners)(store.dispatch, props.setupListeners); }, [props.setupListeners, store.dispatch]);
return /* @__PURE__ */ import_react5.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=rtk-query-react.cjs.development.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,460 @@
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, useDebugValue, useEffect as useEffect3, useLayoutEffect, useMemo as useMemo2, useRef as useRef3, useState } from "react";
import { QueryStatus, skipToken } from "@reduxjs/toolkit/query";
import { shallowEqual as shallowEqual2 } from "react-redux";
// src/query/react/useSerializedStableValue.ts
import { useEffect, useRef, useMemo } from "react";
function useStableQueryArgs(queryArgs, serialize, endpointDefinition, endpointName) {
var incoming = useMemo(function () { return ({
queryArgs: queryArgs,
serialized: typeof queryArgs == "object" ? serialize({ queryArgs: queryArgs, endpointDefinition: endpointDefinition, endpointName: endpointName }) : queryArgs
}); }, [queryArgs, serialize, endpointDefinition, endpointName]);
var cache2 = useRef(incoming);
useEffect(function () {
if (cache2.current.serialized !== incoming.serialized) {
cache2.current = incoming;
}
}, [incoming]);
return cache2.current.serialized === incoming.serialized ? cache2.current.queryArgs : queryArgs;
}
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/useShallowStableValue.ts
import { useEffect as useEffect2, useRef as useRef2 } from "react";
import { shallowEqual } from "react-redux";
function useShallowStableValue(value) {
var cache2 = useRef2(value);
useEffect2(function () {
if (!shallowEqual(cache2.current, value)) {
cache2.current = value;
}
}, [value]);
return shallowEqual(cache2.current, value) ? cache2.current : value;
}
// src/query/defaultSerializeQueryArgs.ts
import { isPlainObject } from "@reduxjs/toolkit";
var cache = WeakMap ? new WeakMap() : void 0;
var defaultSerializeQueryArgs = function (_c) {
var endpointName = _c.endpointName, queryArgs = _c.queryArgs;
var serialized = "";
var cached = cache == null ? void 0 : cache.get(queryArgs);
if (typeof cached === "string") {
serialized = cached;
}
else {
var stringified = JSON.stringify(queryArgs, function (key, value) { return isPlainObject(value) ? Object.keys(value).sort().reduce(function (acc, key2) {
acc[key2] = value[key2];
return acc;
}, {}) : value; });
if (isPlainObject(queryArgs)) {
cache == null ? void 0 : cache.set(queryArgs, stringified);
}
serialized = stringified;
}
return endpointName + "(" + serialized + ")";
};
// src/query/react/buildHooks.ts
var useIsomorphicLayoutEffect = typeof window !== "undefined" && !!window.document && !!window.document.createElement ? useLayoutEffect : useEffect3;
var defaultMutationStateSelector = function (x) { return x; };
var noPendingQueryStateSelector = function (selected) {
if (selected.isUninitialized) {
return __spreadProps(__spreadValues({}, selected), {
isUninitialized: false,
isFetching: true,
isLoading: selected.data !== void 0 ? false : true,
status: QueryStatus.pending
});
}
return selected;
};
function buildHooks(_c) {
var api = _c.api, _d = _c.moduleOptions, batch = _d.batch, useDispatch = _d.useDispatch, useSelector = _d.useSelector, useStore = _d.useStore, unstable__sideEffectsInRender = _d.unstable__sideEffectsInRender, serializeQueryArgs = _c.serializeQueryArgs, context = _c.context;
var usePossiblyImmediateEffect = unstable__sideEffectsInRender ? function (cb) { return cb(); } : useEffect3;
return { buildQueryHooks: buildQueryHooks, buildMutationHook: buildMutationHook, usePrefetch: usePrefetch };
function queryStatePreSelector(currentState, lastResult, queryArgs) {
if ((lastResult == null ? void 0 : lastResult.endpointName) && currentState.isUninitialized) {
var endpointName = lastResult.endpointName;
var endpointDefinition = context.endpointDefinitions[endpointName];
if (serializeQueryArgs({
queryArgs: lastResult.originalArgs,
endpointDefinition: endpointDefinition,
endpointName: endpointName
}) === serializeQueryArgs({
queryArgs: queryArgs,
endpointDefinition: endpointDefinition,
endpointName: endpointName
}))
lastResult = void 0;
}
var data = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data;
if (data === void 0)
data = currentState.data;
var hasData = data !== void 0;
var isFetching = currentState.isLoading;
var isLoading = !hasData && isFetching;
var isSuccess = currentState.isSuccess || isFetching && hasData;
return __spreadProps(__spreadValues({}, currentState), {
data: data,
currentData: currentState.data,
isFetching: isFetching,
isLoading: isLoading,
isSuccess: isSuccess
});
}
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 = useStableQueryArgs(skip ? skipToken : arg, defaultSerializeQueryArgs, context.endpointDefinitions[name], name);
var stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect: refetchOnReconnect,
refetchOnFocus: refetchOnFocus,
pollingInterval: pollingInterval
});
var lastRenderHadSubscription = useRef3(false);
var promiseRef = useRef3();
var _g = promiseRef.current || {}, queryCacheKey = _g.queryCacheKey, requestId = _g.requestId;
var currentRenderHasSubscription = false;
if (queryCacheKey && requestId) {
var returnedValue = dispatch(api.internalActions.internal_probeSubscription({
queryCacheKey: queryCacheKey,
requestId: requestId
}));
if (process.env.NODE_ENV !== "production") {
if (typeof returnedValue !== "boolean") {
throw new Error("Warning: Middleware for RTK-Query API at reducerPath \"" + api.reducerPath + "\" has not been added to the store.\n You must add the middleware for RTK-Query to function correctly!");
}
}
currentRenderHasSubscription = !!returnedValue;
}
var subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;
usePossiblyImmediateEffect(function () {
lastRenderHadSubscription.current = currentRenderHasSubscription;
});
usePossiblyImmediateEffect(function () {
if (subscriptionRemoved) {
promiseRef.current = void 0;
}
}, [subscriptionRemoved]);
usePossiblyImmediateEffect(function () {
var _a;
var lastPromise = promiseRef.current;
if (typeof process !== "undefined" && process.env.NODE_ENV === "removeMeOnCompilation") {
console.log(subscriptionRemoved);
}
if (stableArg === skipToken) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
promiseRef.current = void 0;
return;
}
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,
subscriptionRemoved
]);
useEffect3(function () {
return function () {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return useMemo2(function () { return ({
refetch: function () {
var _a;
if (!promiseRef.current)
throw new Error("Cannot refetch a query that has not been started yet.");
return (_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 = useRef3();
var stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect: refetchOnReconnect,
refetchOnFocus: refetchOnFocus,
pollingInterval: pollingInterval
});
usePossiblyImmediateEffect(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 = useRef3(stableSubscriptionOptions);
usePossiblyImmediateEffect(function () {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
var trigger = useCallback(function (arg2, preferCacheValue) {
if (preferCacheValue === void 0) { preferCacheValue = false; }
var promise;
batch(function () {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = promise = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
return promise;
}, [dispatch, initiate]);
useEffect3(function () {
return function () {
var _a;
(_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
};
}, []);
useEffect3(function () {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return useMemo2(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, selectFromResult = _d.selectFromResult;
var select = api.endpoints[name].select;
var stableArg = useStableQueryArgs(skip ? skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);
var lastValue = useRef3();
var selectDefaultResult = useMemo2(function () { return createSelector([
select(stableArg),
function (_, lastResult) { return lastResult; },
function (_) { return stableArg; }
], queryStatePreSelector); }, [select, stableArg]);
var querySelector = useMemo2(function () { return selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult; }, [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 = useMemo2(function () { return ({ lastArg: arg }); }, [arg]);
return useMemo2(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));
var data = queryStateResults.data, status = queryStateResults.status, isLoading = queryStateResults.isLoading, isSuccess = queryStateResults.isSuccess, isError = queryStateResults.isError, error = queryStateResults.error;
useDebugValue({ data: data, status: status, isLoading: isLoading, isSuccess: isSuccess, isError: isError, error: error });
return useMemo2(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, fixedCacheKey = _d.fixedCacheKey;
var _f = api.endpoints[name], select = _f.select, initiate = _f.initiate;
var dispatch = useDispatch();
var _g = useState(), promise = _g[0], setPromise = _g[1];
useEffect3(function () { return function () {
if (!(promise == null ? void 0 : promise.arg.fixedCacheKey)) {
promise == null ? void 0 : promise.reset();
}
}; }, [promise]);
var triggerMutation = useCallback(function (arg) {
var promise2 = dispatch(initiate(arg, { fixedCacheKey: fixedCacheKey }));
setPromise(promise2);
return promise2;
}, [dispatch, initiate, fixedCacheKey]);
var requestId = (promise || {}).requestId;
var mutationSelector = useMemo2(function () { return createSelector([select({ fixedCacheKey: fixedCacheKey, requestId: promise == null ? void 0 : promise.requestId })], selectFromResult); }, [select, promise, selectFromResult, fixedCacheKey]);
var currentState = useSelector(mutationSelector, shallowEqual2);
var originalArgs = fixedCacheKey == null ? promise == null ? void 0 : promise.arg.originalArgs : void 0;
var reset = useCallback(function () {
batch(function () {
if (promise) {
setPromise(void 0);
}
if (fixedCacheKey) {
dispatch(api.internalActions.removeMutationResult({
requestId: requestId,
fixedCacheKey: fixedCacheKey
}));
}
});
}, [dispatch, fixedCacheKey, promise, requestId]);
var endpointName = currentState.endpointName, data = currentState.data, status = currentState.status, isLoading = currentState.isLoading, isSuccess = currentState.isSuccess, isError = currentState.isError, error = currentState.error;
useDebugValue({
endpointName: endpointName,
data: data,
status: status,
isLoading: isLoading,
isSuccess: isSuccess,
isError: isError,
error: error
});
var finalState = useMemo2(function () { return __spreadProps(__spreadValues({}, currentState), { originalArgs: originalArgs, reset: reset }); }, [currentState, originalArgs, reset]);
return useMemo2(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, _j = _d.unstable__sideEffectsInRender, unstable__sideEffectsInRender = _j === void 0 ? false : _j;
return ({
name: reactHooksModuleName,
init: function (api, _c, context) {
var serializeQueryArgs = _c.serializeQueryArgs;
var anyApi = api;
var _d = buildHooks({
api: api,
moduleOptions: {
batch: batch,
useDispatch: useDispatch,
useSelector: useSelector,
useStore: useStore,
unstable__sideEffectsInRender: unstable__sideEffectsInRender
},
serializeQueryArgs: serializeQueryArgs,
context: context
}), buildQueryHooks = _d.buildQueryHooks, buildMutationHook = _d.buildMutationHook, usePrefetch = _d.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 { useEffect as useEffect4 } from "react";
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];
useEffect4(function () { return props.setupListeners === false ? void 0 : setupListeners(store.dispatch, props.setupListeners); }, [props.setupListeners, store.dispatch]);
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, reactHooksModuleName };
//# sourceMappingURL=rtk-query-react.esm.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,437 @@
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, useDebugValue, useEffect as useEffect3, useLayoutEffect, useMemo as useMemo2, useRef as useRef3, useState } from "react";
import { QueryStatus, skipToken } from "@reduxjs/toolkit/query";
import { shallowEqual as shallowEqual2 } from "react-redux";
// src/query/react/useSerializedStableValue.ts
import { useEffect, useRef, useMemo } from "react";
function useStableQueryArgs(queryArgs, serialize, endpointDefinition, endpointName) {
const incoming = useMemo(() => ({
queryArgs,
serialized: typeof queryArgs == "object" ? serialize({ queryArgs, endpointDefinition, endpointName }) : queryArgs
}), [queryArgs, serialize, endpointDefinition, endpointName]);
const cache2 = useRef(incoming);
useEffect(() => {
if (cache2.current.serialized !== incoming.serialized) {
cache2.current = incoming;
}
}, [incoming]);
return cache2.current.serialized === incoming.serialized ? cache2.current.queryArgs : queryArgs;
}
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/useShallowStableValue.ts
import { useEffect as useEffect2, useRef as useRef2 } from "react";
import { shallowEqual } from "react-redux";
function useShallowStableValue(value) {
const cache2 = useRef2(value);
useEffect2(() => {
if (!shallowEqual(cache2.current, value)) {
cache2.current = value;
}
}, [value]);
return shallowEqual(cache2.current, value) ? cache2.current : value;
}
// src/query/defaultSerializeQueryArgs.ts
import { isPlainObject } from "@reduxjs/toolkit";
var cache = WeakMap ? new WeakMap() : void 0;
var defaultSerializeQueryArgs = ({ endpointName, queryArgs }) => {
let serialized = "";
const cached = cache == null ? void 0 : cache.get(queryArgs);
if (typeof cached === "string") {
serialized = cached;
}
else {
const stringified = JSON.stringify(queryArgs, (key, value) => isPlainObject(value) ? Object.keys(value).sort().reduce((acc, key2) => {
acc[key2] = value[key2];
return acc;
}, {}) : value);
if (isPlainObject(queryArgs)) {
cache == null ? void 0 : cache.set(queryArgs, stringified);
}
serialized = stringified;
}
return `${endpointName}(${serialized})`;
};
// src/query/react/buildHooks.ts
var useIsomorphicLayoutEffect = typeof window !== "undefined" && !!window.document && !!window.document.createElement ? useLayoutEffect : useEffect3;
var defaultMutationStateSelector = (x) => x;
var noPendingQueryStateSelector = (selected) => {
if (selected.isUninitialized) {
return __spreadProps(__spreadValues({}, selected), {
isUninitialized: false,
isFetching: true,
isLoading: selected.data !== void 0 ? false : true,
status: QueryStatus.pending
});
}
return selected;
};
function buildHooks({ api, moduleOptions: { batch, useDispatch, useSelector, useStore, unstable__sideEffectsInRender }, serializeQueryArgs, context }) {
const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : useEffect3;
return { buildQueryHooks, buildMutationHook, usePrefetch };
function queryStatePreSelector(currentState, lastResult, queryArgs) {
if ((lastResult == null ? void 0 : lastResult.endpointName) && currentState.isUninitialized) {
const { endpointName } = lastResult;
const endpointDefinition = context.endpointDefinitions[endpointName];
if (serializeQueryArgs({
queryArgs: lastResult.originalArgs,
endpointDefinition,
endpointName
}) === serializeQueryArgs({
queryArgs,
endpointDefinition,
endpointName
}))
lastResult = void 0;
}
let data = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data;
if (data === void 0)
data = currentState.data;
const hasData = data !== void 0;
const isFetching = currentState.isLoading;
const isLoading = !hasData && isFetching;
const isSuccess = currentState.isSuccess || isFetching && hasData;
return __spreadProps(__spreadValues({}, currentState), {
data,
currentData: currentState.data,
isFetching,
isLoading,
isSuccess
});
}
function usePrefetch(endpointName, defaultOptions) {
const dispatch = useDispatch();
const stableDefaultOptions = useShallowStableValue(defaultOptions);
return useCallback((arg, options) => dispatch(api.util.prefetch(endpointName, arg, __spreadValues(__spreadValues({}, stableDefaultOptions), options))), [endpointName, dispatch, stableDefaultOptions]);
}
function buildQueryHooks(name) {
const useQuerySubscription = (arg, { refetchOnReconnect, refetchOnFocus, refetchOnMountOrArgChange, skip = false, pollingInterval = 0 } = {}) => {
const { initiate } = api.endpoints[name];
const dispatch = useDispatch();
const stableArg = useStableQueryArgs(skip ? skipToken : arg, defaultSerializeQueryArgs, context.endpointDefinitions[name], name);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval
});
const lastRenderHadSubscription = useRef3(false);
const promiseRef = useRef3();
let { queryCacheKey, requestId } = promiseRef.current || {};
let currentRenderHasSubscription = false;
if (queryCacheKey && requestId) {
const returnedValue = dispatch(api.internalActions.internal_probeSubscription({
queryCacheKey,
requestId
}));
if (true) {
if (typeof returnedValue !== "boolean") {
throw new Error(`Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
You must add the middleware for RTK-Query to function correctly!`);
}
}
currentRenderHasSubscription = !!returnedValue;
}
const subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;
usePossiblyImmediateEffect(() => {
lastRenderHadSubscription.current = currentRenderHasSubscription;
});
usePossiblyImmediateEffect(() => {
if (subscriptionRemoved) {
promiseRef.current = void 0;
}
}, [subscriptionRemoved]);
usePossiblyImmediateEffect(() => {
var _a;
const lastPromise = promiseRef.current;
if (typeof process !== "undefined" && false) {
console.log(subscriptionRemoved);
}
if (stableArg === skipToken) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
promiseRef.current = void 0;
return;
}
const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (!lastPromise || lastPromise.arg !== stableArg) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
const promise = dispatch(initiate(stableArg, {
subscriptionOptions: stableSubscriptionOptions,
forceRefetch: refetchOnMountOrArgChange
}));
promiseRef.current = promise;
}
else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [
dispatch,
initiate,
refetchOnMountOrArgChange,
stableArg,
stableSubscriptionOptions,
subscriptionRemoved
]);
useEffect3(() => {
return () => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return useMemo2(() => ({
refetch: () => {
var _a;
if (!promiseRef.current)
throw new Error("Cannot refetch a query that has not been started yet.");
return (_a = promiseRef.current) == null ? void 0 : _a.refetch();
}
}), []);
};
const useLazyQuerySubscription = ({ refetchOnReconnect, refetchOnFocus, pollingInterval = 0 } = {}) => {
const { initiate } = api.endpoints[name];
const dispatch = useDispatch();
const [arg, setArg] = useState(UNINITIALIZED_VALUE);
const promiseRef = useRef3();
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval
});
usePossiblyImmediateEffect(() => {
var _a, _b;
const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (stableSubscriptionOptions !== lastSubscriptionOptions) {
(_b = promiseRef.current) == null ? void 0 : _b.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [stableSubscriptionOptions]);
const subscriptionOptionsRef = useRef3(stableSubscriptionOptions);
usePossiblyImmediateEffect(() => {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
const trigger = useCallback(function (arg2, preferCacheValue = false) {
let promise;
batch(() => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = promise = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
return promise;
}, [dispatch, initiate]);
useEffect3(() => {
return () => {
var _a;
(_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
};
}, []);
useEffect3(() => {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return useMemo2(() => [trigger, arg], [trigger, arg]);
};
const useQueryState = (arg, { skip = false, selectFromResult } = {}) => {
const { select } = api.endpoints[name];
const stableArg = useStableQueryArgs(skip ? skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);
const lastValue = useRef3();
const selectDefaultResult = useMemo2(() => createSelector([
select(stableArg),
(_, lastResult) => lastResult,
(_) => stableArg
], queryStatePreSelector), [select, stableArg]);
const querySelector = useMemo2(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectDefaultResult, selectFromResult]);
const currentState = useSelector((state) => querySelector(state, lastValue.current), shallowEqual2);
const store = useStore();
const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
useIsomorphicLayoutEffect(() => {
lastValue.current = newLastValue;
}, [newLastValue]);
return currentState;
};
return {
useQueryState,
useQuerySubscription,
useLazyQuerySubscription,
useLazyQuery(options) {
const [trigger, arg] = useLazyQuerySubscription(options);
const queryStateResults = useQueryState(arg, __spreadProps(__spreadValues({}, options), {
skip: arg === UNINITIALIZED_VALUE
}));
const info = useMemo2(() => ({ lastArg: arg }), [arg]);
return useMemo2(() => [trigger, queryStateResults, info], [trigger, queryStateResults, info]);
},
useQuery(arg, options) {
const querySubscriptionResults = useQuerySubscription(arg, options);
const queryStateResults = useQueryState(arg, __spreadValues({
selectFromResult: arg === skipToken || (options == null ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector
}, options));
const { data, status, isLoading, isSuccess, isError, error } = queryStateResults;
useDebugValue({ data, status, isLoading, isSuccess, isError, error });
return useMemo2(() => __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults), [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return ({ selectFromResult = defaultMutationStateSelector, fixedCacheKey } = {}) => {
const { select, initiate } = api.endpoints[name];
const dispatch = useDispatch();
const [promise, setPromise] = useState();
useEffect3(() => () => {
if (!(promise == null ? void 0 : promise.arg.fixedCacheKey)) {
promise == null ? void 0 : promise.reset();
}
}, [promise]);
const triggerMutation = useCallback(function (arg) {
const promise2 = dispatch(initiate(arg, { fixedCacheKey }));
setPromise(promise2);
return promise2;
}, [dispatch, initiate, fixedCacheKey]);
const { requestId } = promise || {};
const mutationSelector = useMemo2(() => createSelector([select({ fixedCacheKey, requestId: promise == null ? void 0 : promise.requestId })], selectFromResult), [select, promise, selectFromResult, fixedCacheKey]);
const currentState = useSelector(mutationSelector, shallowEqual2);
const originalArgs = fixedCacheKey == null ? promise == null ? void 0 : promise.arg.originalArgs : void 0;
const reset = useCallback(() => {
batch(() => {
if (promise) {
setPromise(void 0);
}
if (fixedCacheKey) {
dispatch(api.internalActions.removeMutationResult({
requestId,
fixedCacheKey
}));
}
});
}, [dispatch, fixedCacheKey, promise, requestId]);
const { endpointName, data, status, isLoading, isSuccess, isError, error } = currentState;
useDebugValue({
endpointName,
data,
status,
isLoading,
isSuccess,
isError,
error
});
const finalState = useMemo2(() => __spreadProps(__spreadValues({}, currentState), { originalArgs, reset }), [currentState, originalArgs, reset]);
return useMemo2(() => [triggerMutation, finalState], [triggerMutation, finalState]);
};
}
}
// src/query/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, unstable__sideEffectsInRender = false } = {}) => ({
name: reactHooksModuleName,
init(api, { serializeQueryArgs }, context) {
const anyApi = api;
const { buildQueryHooks, buildMutationHook, usePrefetch } = buildHooks({
api,
moduleOptions: {
batch,
useDispatch,
useSelector,
useStore,
unstable__sideEffectsInRender
},
serializeQueryArgs,
context
});
safeAssign(anyApi, { usePrefetch });
safeAssign(context, { batch });
return {
injectEndpoint(endpointName, definition) {
if (isQueryDefinition(definition)) {
const { useQuery, useLazyQuery, useLazyQuerySubscription, useQueryState, useQuerySubscription } = buildQueryHooks(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription
});
api[`use${capitalize(endpointName)}Query`] = useQuery;
api[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;
}
else if (isMutationDefinition(definition)) {
const useMutation = buildMutationHook(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useMutation
});
api[`use${capitalize(endpointName)}Mutation`] = useMutation;
}
}
};
}
});
// src/query/react/index.ts
export * from "@reduxjs/toolkit/query";
// src/query/react/ApiProvider.tsx
import { configureStore } from "@reduxjs/toolkit";
import { useEffect as useEffect4 } from "react";
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)
}));
useEffect4(() => props.setupListeners === false ? void 0 : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);
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, reactHooksModuleName };
//# sourceMappingURL=rtk-query-react.modern.development.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,437 @@
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, useDebugValue, useEffect as useEffect3, useLayoutEffect, useMemo as useMemo2, useRef as useRef3, useState } from "react";
import { QueryStatus, skipToken } from "@reduxjs/toolkit/query";
import { shallowEqual as shallowEqual2 } from "react-redux";
// src/query/react/useSerializedStableValue.ts
import { useEffect, useRef, useMemo } from "react";
function useStableQueryArgs(queryArgs, serialize, endpointDefinition, endpointName) {
const incoming = useMemo(() => ({
queryArgs,
serialized: typeof queryArgs == "object" ? serialize({ queryArgs, endpointDefinition, endpointName }) : queryArgs
}), [queryArgs, serialize, endpointDefinition, endpointName]);
const cache2 = useRef(incoming);
useEffect(() => {
if (cache2.current.serialized !== incoming.serialized) {
cache2.current = incoming;
}
}, [incoming]);
return cache2.current.serialized === incoming.serialized ? cache2.current.queryArgs : queryArgs;
}
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/useShallowStableValue.ts
import { useEffect as useEffect2, useRef as useRef2 } from "react";
import { shallowEqual } from "react-redux";
function useShallowStableValue(value) {
const cache2 = useRef2(value);
useEffect2(() => {
if (!shallowEqual(cache2.current, value)) {
cache2.current = value;
}
}, [value]);
return shallowEqual(cache2.current, value) ? cache2.current : value;
}
// src/query/defaultSerializeQueryArgs.ts
import { isPlainObject } from "@reduxjs/toolkit";
var cache = WeakMap ? new WeakMap() : void 0;
var defaultSerializeQueryArgs = ({ endpointName, queryArgs }) => {
let serialized = "";
const cached = cache == null ? void 0 : cache.get(queryArgs);
if (typeof cached === "string") {
serialized = cached;
}
else {
const stringified = JSON.stringify(queryArgs, (key, value) => isPlainObject(value) ? Object.keys(value).sort().reduce((acc, key2) => {
acc[key2] = value[key2];
return acc;
}, {}) : value);
if (isPlainObject(queryArgs)) {
cache == null ? void 0 : cache.set(queryArgs, stringified);
}
serialized = stringified;
}
return `${endpointName}(${serialized})`;
};
// src/query/react/buildHooks.ts
var useIsomorphicLayoutEffect = typeof window !== "undefined" && !!window.document && !!window.document.createElement ? useLayoutEffect : useEffect3;
var defaultMutationStateSelector = (x) => x;
var noPendingQueryStateSelector = (selected) => {
if (selected.isUninitialized) {
return __spreadProps(__spreadValues({}, selected), {
isUninitialized: false,
isFetching: true,
isLoading: selected.data !== void 0 ? false : true,
status: QueryStatus.pending
});
}
return selected;
};
function buildHooks({ api, moduleOptions: { batch, useDispatch, useSelector, useStore, unstable__sideEffectsInRender }, serializeQueryArgs, context }) {
const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : useEffect3;
return { buildQueryHooks, buildMutationHook, usePrefetch };
function queryStatePreSelector(currentState, lastResult, queryArgs) {
if ((lastResult == null ? void 0 : lastResult.endpointName) && currentState.isUninitialized) {
const { endpointName } = lastResult;
const endpointDefinition = context.endpointDefinitions[endpointName];
if (serializeQueryArgs({
queryArgs: lastResult.originalArgs,
endpointDefinition,
endpointName
}) === serializeQueryArgs({
queryArgs,
endpointDefinition,
endpointName
}))
lastResult = void 0;
}
let data = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data;
if (data === void 0)
data = currentState.data;
const hasData = data !== void 0;
const isFetching = currentState.isLoading;
const isLoading = !hasData && isFetching;
const isSuccess = currentState.isSuccess || isFetching && hasData;
return __spreadProps(__spreadValues({}, currentState), {
data,
currentData: currentState.data,
isFetching,
isLoading,
isSuccess
});
}
function usePrefetch(endpointName, defaultOptions) {
const dispatch = useDispatch();
const stableDefaultOptions = useShallowStableValue(defaultOptions);
return useCallback((arg, options) => dispatch(api.util.prefetch(endpointName, arg, __spreadValues(__spreadValues({}, stableDefaultOptions), options))), [endpointName, dispatch, stableDefaultOptions]);
}
function buildQueryHooks(name) {
const useQuerySubscription = (arg, { refetchOnReconnect, refetchOnFocus, refetchOnMountOrArgChange, skip = false, pollingInterval = 0 } = {}) => {
const { initiate } = api.endpoints[name];
const dispatch = useDispatch();
const stableArg = useStableQueryArgs(skip ? skipToken : arg, defaultSerializeQueryArgs, context.endpointDefinitions[name], name);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval
});
const lastRenderHadSubscription = useRef3(false);
const promiseRef = useRef3();
let { queryCacheKey, requestId } = promiseRef.current || {};
let currentRenderHasSubscription = false;
if (queryCacheKey && requestId) {
const returnedValue = dispatch(api.internalActions.internal_probeSubscription({
queryCacheKey,
requestId
}));
if (process.env.NODE_ENV !== "production") {
if (typeof returnedValue !== "boolean") {
throw new Error(`Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
You must add the middleware for RTK-Query to function correctly!`);
}
}
currentRenderHasSubscription = !!returnedValue;
}
const subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;
usePossiblyImmediateEffect(() => {
lastRenderHadSubscription.current = currentRenderHasSubscription;
});
usePossiblyImmediateEffect(() => {
if (subscriptionRemoved) {
promiseRef.current = void 0;
}
}, [subscriptionRemoved]);
usePossiblyImmediateEffect(() => {
var _a;
const lastPromise = promiseRef.current;
if (typeof process !== "undefined" && process.env.NODE_ENV === "removeMeOnCompilation") {
console.log(subscriptionRemoved);
}
if (stableArg === skipToken) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
promiseRef.current = void 0;
return;
}
const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (!lastPromise || lastPromise.arg !== stableArg) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
const promise = dispatch(initiate(stableArg, {
subscriptionOptions: stableSubscriptionOptions,
forceRefetch: refetchOnMountOrArgChange
}));
promiseRef.current = promise;
}
else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [
dispatch,
initiate,
refetchOnMountOrArgChange,
stableArg,
stableSubscriptionOptions,
subscriptionRemoved
]);
useEffect3(() => {
return () => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return useMemo2(() => ({
refetch: () => {
var _a;
if (!promiseRef.current)
throw new Error("Cannot refetch a query that has not been started yet.");
return (_a = promiseRef.current) == null ? void 0 : _a.refetch();
}
}), []);
};
const useLazyQuerySubscription = ({ refetchOnReconnect, refetchOnFocus, pollingInterval = 0 } = {}) => {
const { initiate } = api.endpoints[name];
const dispatch = useDispatch();
const [arg, setArg] = useState(UNINITIALIZED_VALUE);
const promiseRef = useRef3();
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval
});
usePossiblyImmediateEffect(() => {
var _a, _b;
const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (stableSubscriptionOptions !== lastSubscriptionOptions) {
(_b = promiseRef.current) == null ? void 0 : _b.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [stableSubscriptionOptions]);
const subscriptionOptionsRef = useRef3(stableSubscriptionOptions);
usePossiblyImmediateEffect(() => {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
const trigger = useCallback(function (arg2, preferCacheValue = false) {
let promise;
batch(() => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = promise = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
return promise;
}, [dispatch, initiate]);
useEffect3(() => {
return () => {
var _a;
(_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
};
}, []);
useEffect3(() => {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return useMemo2(() => [trigger, arg], [trigger, arg]);
};
const useQueryState = (arg, { skip = false, selectFromResult } = {}) => {
const { select } = api.endpoints[name];
const stableArg = useStableQueryArgs(skip ? skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);
const lastValue = useRef3();
const selectDefaultResult = useMemo2(() => createSelector([
select(stableArg),
(_, lastResult) => lastResult,
(_) => stableArg
], queryStatePreSelector), [select, stableArg]);
const querySelector = useMemo2(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectDefaultResult, selectFromResult]);
const currentState = useSelector((state) => querySelector(state, lastValue.current), shallowEqual2);
const store = useStore();
const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
useIsomorphicLayoutEffect(() => {
lastValue.current = newLastValue;
}, [newLastValue]);
return currentState;
};
return {
useQueryState,
useQuerySubscription,
useLazyQuerySubscription,
useLazyQuery(options) {
const [trigger, arg] = useLazyQuerySubscription(options);
const queryStateResults = useQueryState(arg, __spreadProps(__spreadValues({}, options), {
skip: arg === UNINITIALIZED_VALUE
}));
const info = useMemo2(() => ({ lastArg: arg }), [arg]);
return useMemo2(() => [trigger, queryStateResults, info], [trigger, queryStateResults, info]);
},
useQuery(arg, options) {
const querySubscriptionResults = useQuerySubscription(arg, options);
const queryStateResults = useQueryState(arg, __spreadValues({
selectFromResult: arg === skipToken || (options == null ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector
}, options));
const { data, status, isLoading, isSuccess, isError, error } = queryStateResults;
useDebugValue({ data, status, isLoading, isSuccess, isError, error });
return useMemo2(() => __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults), [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return ({ selectFromResult = defaultMutationStateSelector, fixedCacheKey } = {}) => {
const { select, initiate } = api.endpoints[name];
const dispatch = useDispatch();
const [promise, setPromise] = useState();
useEffect3(() => () => {
if (!(promise == null ? void 0 : promise.arg.fixedCacheKey)) {
promise == null ? void 0 : promise.reset();
}
}, [promise]);
const triggerMutation = useCallback(function (arg) {
const promise2 = dispatch(initiate(arg, { fixedCacheKey }));
setPromise(promise2);
return promise2;
}, [dispatch, initiate, fixedCacheKey]);
const { requestId } = promise || {};
const mutationSelector = useMemo2(() => createSelector([select({ fixedCacheKey, requestId: promise == null ? void 0 : promise.requestId })], selectFromResult), [select, promise, selectFromResult, fixedCacheKey]);
const currentState = useSelector(mutationSelector, shallowEqual2);
const originalArgs = fixedCacheKey == null ? promise == null ? void 0 : promise.arg.originalArgs : void 0;
const reset = useCallback(() => {
batch(() => {
if (promise) {
setPromise(void 0);
}
if (fixedCacheKey) {
dispatch(api.internalActions.removeMutationResult({
requestId,
fixedCacheKey
}));
}
});
}, [dispatch, fixedCacheKey, promise, requestId]);
const { endpointName, data, status, isLoading, isSuccess, isError, error } = currentState;
useDebugValue({
endpointName,
data,
status,
isLoading,
isSuccess,
isError,
error
});
const finalState = useMemo2(() => __spreadProps(__spreadValues({}, currentState), { originalArgs, reset }), [currentState, originalArgs, reset]);
return useMemo2(() => [triggerMutation, finalState], [triggerMutation, finalState]);
};
}
}
// src/query/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, unstable__sideEffectsInRender = false } = {}) => ({
name: reactHooksModuleName,
init(api, { serializeQueryArgs }, context) {
const anyApi = api;
const { buildQueryHooks, buildMutationHook, usePrefetch } = buildHooks({
api,
moduleOptions: {
batch,
useDispatch,
useSelector,
useStore,
unstable__sideEffectsInRender
},
serializeQueryArgs,
context
});
safeAssign(anyApi, { usePrefetch });
safeAssign(context, { batch });
return {
injectEndpoint(endpointName, definition) {
if (isQueryDefinition(definition)) {
const { useQuery, useLazyQuery, useLazyQuerySubscription, useQueryState, useQuerySubscription } = buildQueryHooks(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription
});
api[`use${capitalize(endpointName)}Query`] = useQuery;
api[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;
}
else if (isMutationDefinition(definition)) {
const useMutation = buildMutationHook(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useMutation
});
api[`use${capitalize(endpointName)}Mutation`] = useMutation;
}
}
};
}
});
// src/query/react/index.ts
export * from "@reduxjs/toolkit/query";
// src/query/react/ApiProvider.tsx
import { configureStore } from "@reduxjs/toolkit";
import { useEffect as useEffect4 } from "react";
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)
}));
useEffect4(() => props.setupListeners === false ? void 0 : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);
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, reactHooksModuleName };
//# sourceMappingURL=rtk-query-react.modern.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,3 @@
import type { SerializeQueryArgs } from '@reduxjs/toolkit/query';
import type { EndpointDefinition } from '@reduxjs/toolkit/query';
export declare function useStableQueryArgs<T>(queryArgs: T, serialize: SerializeQueryArgs<any>, endpointDefinition: EndpointDefinition<any, any, any, any>, endpointName: string): T;

View File

@@ -0,0 +1 @@
export declare function useShallowStableValue<T>(value: T): T;

63
node_modules/@reduxjs/toolkit/dist/query/retry.d.ts generated vendored Normal file
View File

@@ -0,0 +1,63 @@
import type { BaseQueryApi, BaseQueryArg, BaseQueryEnhancer, BaseQueryExtraOptions, BaseQueryFn } from './baseQueryTypes';
import type { FetchBaseQueryError } from './fetchBaseQuery';
declare type RetryConditionFunction = (error: FetchBaseQueryError, args: BaseQueryArg<BaseQueryFn>, extraArgs: {
attempt: number;
baseQueryApi: BaseQueryApi;
extraOptions: BaseQueryExtraOptions<BaseQueryFn> & RetryOptions;
}) => boolean;
export declare type RetryOptions = {
/**
* Function used to determine delay between retries
*/
backoff?: (attempt: number, maxRetries: number) => Promise<void>;
} & ({
/**
* How many times the query will be retried (default: 5)
*/
maxRetries?: number;
retryCondition?: undefined;
} | {
/**
* Callback to determine if a retry should be attempted.
* Return `true` for another retry and `false` to quit trying prematurely.
*/
retryCondition?: RetryConditionFunction;
maxRetries?: undefined;
});
declare function fail(e: any): never;
/**
* A utility that can wrap `baseQuery` in the API definition to provide retries with a basic exponential backoff.
*
* @example
*
* ```ts
* // codeblock-meta title="Retry every request 5 times by default"
* import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
* type PostsResponse = Post[]
*
* // maxRetries: 5 is the default, and can be omitted. Shown for documentation purposes.
* const staggeredBaseQuery = retry(fetchBaseQuery({ baseUrl: '/' }), { maxRetries: 5 });
* export const api = createApi({
* baseQuery: staggeredBaseQuery,
* endpoints: (build) => ({
* getPosts: build.query<PostsResponse, void>({
* query: () => ({ url: 'posts' }),
* }),
* getPost: build.query<PostsResponse, string>({
* query: (id) => ({ url: `post/${id}` }),
* extraOptions: { maxRetries: 8 }, // You can override the retry behavior on each endpoint
* }),
* }),
* });
*
* export const { useGetPostsQuery, useGetPostQuery } = api;
* ```
*/
export declare const retry: BaseQueryEnhancer<unknown, RetryOptions, void | RetryOptions> & {
fail: typeof fail;
};
export {};

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

2212
node_modules/@reduxjs/toolkit/dist/query/rtk-query.esm.js generated vendored Normal file

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 it is too large Load Diff

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

3858
node_modules/@reduxjs/toolkit/dist/query/rtk-query.umd.js generated vendored Normal file

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,23 @@
export declare type Id<T> = {
[K in keyof T]: T[K];
} & {};
export declare type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
export declare type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never;
export declare function assertCast<T>(v: any): asserts v is T;
export declare function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>): void;
/**
* Convert a Union type `(A|B)` to an intersection type `(A&B)`
*/
export declare type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
export declare type NonOptionalKeys<T> = {
[K in keyof T]-?: undefined extends T[K] ? never : K;
}[keyof T];
export declare type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never ? False : True;
export declare type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>;
export declare type NoInfer<T> = [T][T extends any ? 0 : never];
export declare type NonUndefined<T> = T extends undefined ? never : T;
export declare type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T;
export declare type MaybePromise<T> = T | PromiseLike<T>;
export declare type OmitFromUnion<T, K extends keyof T> = T extends any ? Omit<T, K> : never;
export declare type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;
export declare type CastAny<T, CastTo> = IsAny<T, CastTo, T>;

View File

@@ -0,0 +1 @@
export declare function capitalize(str: string): string;

View File

@@ -0,0 +1 @@
export declare function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T;

View File

@@ -0,0 +1,6 @@
/**
* Alternative to `Array.flat(1)`
* @param arr An array like [1,2,3,[1,2]]
* @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
*/
export declare const flatten: (arr: readonly any[]) => never[];

View File

@@ -0,0 +1,8 @@
export * from './isAbsoluteUrl';
export * from './isValidUrl';
export * from './joinUrls';
export * from './flatten';
export * from './capitalize';
export * from './isOnline';
export * from './isDocumentVisible';
export * from './copyWithStructuralSharing';

View File

@@ -0,0 +1,6 @@
/**
* If either :// or // is present consider it to be an absolute url
*
* @param url string
*/
export declare function isAbsoluteUrl(url: string): boolean;

View File

@@ -0,0 +1,5 @@
/**
* Assumes true for a non-browser env, otherwise makes a best effort
* @link https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState
*/
export declare function isDocumentVisible(): boolean;

View File

@@ -0,0 +1 @@
export declare function isNotNullish<T>(v: T | null | undefined): v is T;

View File

@@ -0,0 +1,5 @@
/**
* Assumes a browser is online if `undefined`, otherwise makes a best effort
* @link https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine
*/
export declare function isOnline(): boolean;

View File

@@ -0,0 +1 @@
export declare function isValidUrl(string: string): boolean;

View File

@@ -0,0 +1 @@
export declare function joinUrls(base: string | undefined, url: string | undefined): string;