0.2.0 - Mid migration

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

View file

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

View file

@ -0,0 +1,37 @@
import type { EndpointDefinitions, EndpointBuilder, EndpointDefinition, ReplaceTagTypes } from './endpointDefinitions';
import type { UnionToIntersection, NoInfer } from './tsHelpers';
import type { CoreModule } from './core/module';
import type { CreateApiOptions } from './createApi';
import type { BaseQueryFn } from './baseQueryTypes';
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: Required<CreateApiOptions<BaseQuery, Definitions, ReducerPath, 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;
}
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>(_: {
addTagTypes?: readonly NewTagTypes[];
endpoints?: ReplaceTagTypes<Definitions, TagTypes | NoInfer<NewTagTypes>> extends infer NewDefinitions ? {
[K in keyof NewDefinitions]?: Partial<NewDefinitions[K]> | ((definition: NewDefinitions[K]) => void);
} : never;
}): Api<BaseQuery, ReplaceTagTypes<Definitions, TagTypes | NewTagTypes>, ReducerPath, TagTypes | NewTagTypes, Enhancers>;
};

View file

@ -0,0 +1,27 @@
import type { ThunkDispatch } from '@reduxjs/toolkit';
import type { MaybePromise, UnwrapPromise } from './tsHelpers';
export interface BaseQueryApi {
signal: AbortSignal;
dispatch: ThunkDispatch<any, any, any>;
getState: () => unknown;
}
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>;
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,192 @@
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;
};
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>> = {
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'>) | {
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,134 @@
import type { EndpointDefinitions, QueryDefinition, MutationDefinition, QueryArgFrom, ResultTypeFrom } from '../endpointDefinitions';
import type { QueryThunk, MutationThunk } from './buildThunks';
import type { AnyAction, ThunkAction, SerializedError } from '@reduxjs/toolkit';
import type { QuerySubState, SubscriptionOptions } from './apiState';
import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';
import type { Api } from '../apiTypes';
import type { BaseQueryError } from '../baseQueryTypes';
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 interface StartQueryActionCreatorOptions {
subscribe?: boolean;
forceRefetch?: boolean | number;
subscriptionOptions?: SubscriptionOptions;
}
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<QuerySubState<D>> & {
arg: QueryArgFrom<D>;
requestId: string;
subscriptionOptions: SubscriptionOptions | undefined;
abort(): void;
unsubscribe(): void;
refetch(): void;
updateSubscriptionOptions(options: SubscriptionOptions): void;
};
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;
}) => 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;
};
/**
* 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.
*/
unsubscribe(): void;
};
export declare function buildInitiate({ serializeQueryArgs, queryThunk, mutationThunk, api, }: {
serializeQueryArgs: InternalSerializeQueryArgs;
queryThunk: QueryThunk;
mutationThunk: MutationThunk;
api: Api<any, EndpointDefinitions, any, any>;
}): {
buildInitiateQuery: (endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) => StartQueryActionCreator<any>;
buildInitiateMutation: (endpointName: string, definition: MutationDefinition<any, any, any, any>) => StartMutationActionCreator<any>;
};
export {};

View file

@ -0,0 +1,14 @@
import type { BaseQueryFn } from '../../baseQueryTypes';
import type { SubMiddlewareBuilder } 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 build: SubMiddlewareBuilder;

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 { PromiseWithKnownReason, SubMiddlewareBuilder } 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 build: SubMiddlewareBuilder;
export {};

View file

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

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 { SubMiddlewareBuilder } from './types';
export declare const build: SubMiddlewareBuilder;

View file

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

View file

@ -0,0 +1,142 @@
import type { BaseQueryError, BaseQueryFn, BaseQueryMeta } from '../../baseQueryTypes';
import type { SubMiddlewareBuilder, PromiseWithKnownReason } 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` or `transformResponse` 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 build: SubMiddlewareBuilder;

View file

@ -0,0 +1,46 @@
import type { AnyAction, AsyncThunkAction, Middleware, MiddlewareAPI, ThunkDispatch } from '@reduxjs/toolkit';
import type { Api, ApiContext } from '../../apiTypes';
import type { AssertTagTypes, EndpointDefinitions } from '../../endpointDefinitions';
import type { QueryStatus, QuerySubState, RootState } 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 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> {
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 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 { SubMiddlewareBuilder } from './types';
export declare const build: SubMiddlewareBuilder;

View file

@ -0,0 +1,53 @@
import type { MutationSubState, QuerySubState, RootState as _RootState, RequestStatusFlags } from './apiState';
import type { EndpointDefinitions, QueryDefinition, MutationDefinition, QueryArgFrom, TagTypesFrom, ReducerPathFrom } 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 | 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>;
}>;
};
export {};

View file

@ -0,0 +1,34 @@
import { AnyAction, CombinedState, Reducer, ActionCreatorWithPayload, ActionCreatorWithoutPayload } from '@reduxjs/toolkit';
import type { CombinedState as CombinedQueryState, QuerySubstateIdentifier, MutationSubstateIdentifier, Subscribers, ConfigState } from './apiState';
import type { MutationThunk, QueryThunk } from './buildThunks';
import type { AssertTagTypes, EndpointDefinitions } from '../endpointDefinitions';
import type { Patch } from 'immer';
import type { ApiContext } from '../apiTypes';
export declare function buildSlice({ reducerPath, queryThunk, mutationThunk, context: { endpointDefinitions: definitions, apiUid }, assertTagType, config, }: {
reducerPath: string;
queryThunk: QueryThunk;
mutationThunk: MutationThunk;
context: ApiContext<EndpointDefinitions>;
assertTagType: AssertTagTypes;
config: Omit<ConfigState<string>, 'online' | 'focused' | 'middlewareRegistered'>;
}): {
reducer: Reducer<CombinedState<CombinedQueryState<any, string, string>>, AnyAction>;
actions: {
resetApiState: ActionCreatorWithoutPayload<string>;
unsubscribeMutationResult: ActionCreatorWithPayload<MutationSubstateIdentifier, string>;
updateSubscriptionOptions: ActionCreatorWithPayload<{
endpointName: string;
requestId: string;
options: Subscribers[number];
} & QuerySubstateIdentifier, string>;
unsubscribeQueryResult: ActionCreatorWithPayload<{
requestId: string;
} & QuerySubstateIdentifier, string>;
removeQueryResult: ActionCreatorWithPayload<QuerySubstateIdentifier, string>;
queryResultPatched: ActionCreatorWithPayload<QuerySubstateIdentifier & {
patches: readonly Patch[];
}, string>;
middlewareRegistered: ActionCreatorWithPayload<string, string>;
};
};
export declare type SliceActions = ReturnType<typeof buildSlice>['actions'];

View file

@ -0,0 +1,98 @@
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 { CombinedState } from './apiState';
import type { StartQueryActionCreatorOptions } from './buildInitiate';
import type { AssertTagTypes, EndpointDefinition, EndpointDefinitions, MutationDefinition, QueryArgFrom, QueryDefinition, ResultTypeFrom } from '../endpointDefinitions';
import { FullTagDescription } from '../endpointDefinitions';
import type { Draft } from '@reduxjs/toolkit';
import type { Patch } from 'immer';
import type { AnyAction, ThunkAction, AsyncThunk } 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 {
originalArgs: unknown;
endpointName: string;
}
export interface MutationThunkArg {
originalArgs: unknown;
endpointName: string;
track?: boolean;
}
export declare type ThunkResult = unknown;
export declare type ThunkApiMetaConfig = {
pendingMeta: {
startedTimeStamp: number;
};
fulfilledMeta: {
fulfilledTimeStamp: number;
baseQueryMeta: unknown;
};
rejectedMeta: {
baseQueryMeta: unknown;
};
};
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 PatchQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, args: QueryArgFrom<Definitions[EndpointName]>, patches: readonly Patch[]) => 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]>>) => ThunkAction<PatchCollection, 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, }: {
baseQuery: BaseQuery;
reducerPath: ReducerPath;
context: ApiContext<Definitions>;
serializeQueryArgs: InternalSerializeQueryArgs;
api: Api<BaseQuery, Definitions, ReducerPath, any>;
}): {
queryThunk: AsyncThunk<unknown, QueryThunkArg, ThunkApiMetaConfig & {
state: RootState<any, string, ReducerPath>;
}>;
mutationThunk: AsyncThunk<unknown, MutationThunkArg, ThunkApiMetaConfig & {
state: RootState<any, string, ReducerPath>;
}>;
prefetch: <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: any, options: PrefetchOptions) => ThunkAction<void, any, any, AnyAction>;
updateQueryData: UpdateQueryDataThunk<EndpointDefinitions, { [P in ReducerPath]: CombinedState<any, string, P>; }>;
patchQueryData: PatchQueryDataThunk<EndpointDefinitions, { [P in ReducerPath]: 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 };

View file

@ -0,0 +1,225 @@
/**
* Note: this file should import all other files for type discovery and declaration merging
*/
import type { PatchQueryDataThunk, UpdateQueryDataThunk } from './buildThunks';
import './buildThunks';
import type { ActionCreatorWithPayload, AnyAction, Middleware, Reducer, ThunkAction, ThunkDispatch } from '@reduxjs/toolkit';
import type { EndpointDefinitions, QueryArgFrom, QueryDefinition, MutationDefinition, FullTagDescription } from '../endpointDefinitions';
import type { CombinedState, QueryKeys, RootState } from './apiState';
import type { Module } from '../apiTypes';
import { onFocus, onFocusLost, onOnline, onOffline } from './setupListeners';
import './buildSelectors';
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;
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: {
/**
* 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'`), any relevant query arguments, 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'`), any relevant query arguments, and a 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 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.
*
* @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 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'`), any relevant query arguments, 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<TagTypes | FullTagDescription<TagTypes>>, 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> {
}
export interface ApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
}
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;

View file

@ -0,0 +1,162 @@
import type { Api, Module, ModuleName } from './apiTypes';
import type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes';
import type { SerializeQueryArgs } from './defaultSerializeQueryArgs';
import type { EndpointBuilder, EndpointDefinitions } from './endpointDefinitions';
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 an tag type, you will be able to [provide](../../rtk-query/usage/automated-refetching#providing-tags) them with `provides` and [invalidate](../../rtk-query/usage/automated-refetching#invalidating-tags) them with `invalidates` 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;
}
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> = (_: {
queryArgs: QueryArgs;
endpointDefinition: EndpointDefinition<any, any, any, any>;
endpointName: string;
}) => string;
export declare type InternalSerializeQueryArgs = (_: {
queryArgs: any;
endpointDefinition: EndpointDefinition<any, any, any, any>;
endpointName: string;
}) => QueryCacheKey;

View file

@ -0,0 +1,288 @@
import type { AnyAction, ThunkDispatch } from '@reduxjs/toolkit';
import type { RootState } from './core/apiState';
import type { BaseQueryExtraOptions, BaseQueryFn, BaseQueryResult, BaseQueryArg, BaseQueryApi, QueryReturnValue, BaseQueryError, BaseQueryMeta } from './baseQueryTypes';
import type { HasRequiredProps, MaybePromise, OmitFromUnion, CastAny } from './tsHelpers';
import type { NEVER } from './fakeBaseQuery';
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: '/' }),
* endpoints: (build) => ({
* getPosts: build.query<PostsResponse, void>({
* // highlight-start
* query: () => 'posts',
* // highlight-end
* })
* })
* })
* ```
*/
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>): ResultType | Promise<ResultType>;
}
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, 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;
}
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> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg) => 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> = ReadonlyArray<TagDescription<TagTypes>> | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType>;
/** @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 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>>;
/**
* Not to be used. A query should not invalidate tags in the cache.
*/
invalidatesTags?: never;
}
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 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>>;
/**
* Not to be used. A mutation should not provide tags to the cache.
*/
providesTags?: never;
}
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,
* // `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>, 'type'>): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType>;
/**
* 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,
* // `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>(description: ResultDescription<string, ResultType, QueryArg, ErrorType> | undefined, result: ResultType | undefined, error: ErrorType | undefined, queryArg: QueryArg, assertTagTypes: AssertTagTypes): readonly 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>> = D extends EndpointDefinition<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 ReplaceTagTypes<Definitions extends EndpointDefinitions, NewTagTypes extends string> = {
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, NewTagTypes, ResultType, ReducerPath> : Definitions[K] extends MutationDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, NewTagTypes, 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,95 @@
import type { BaseQueryFn } from './baseQueryTypes';
import type { MaybePromise, Override } from './tsHelpers';
export declare type ResponseHandler = '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;
}
export declare type FetchBaseQueryError = {
/**
* * `number`:
* HTTP status code
*/
status: number;
data: unknown;
} | {
/**
* * `"FETCH_ERROR"`:
* An error that occured 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 occured while executing a custom `responseHandler`.
**/
status: 'PARSING_ERROR';
originalStatus: number;
data: string;
error: string;
} | {
/**
* * `"CUSTOM_ERROR"`:
* A custom error type that you can return from your `fetchFn` where another error might not make sense.
**/
status: 'CUSTOM_ERROR';
data?: unknown;
error: string;
};
export declare type FetchBaseQueryArgs = {
baseUrl?: string;
prepareHeaders?: (headers: Headers, api: {
getState: () => unknown;
}) => MaybePromise<Headers>;
fetchFn?: (input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>;
} & RequestInit;
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 http://example.com/
*
* @param {(headers: Headers, api: { getState: () => unknown }) => Headers} prepareHeaders
* An optional function that can be used to inject headers on requests.
* Provides a Headers object, as well as the `getState` function from the
* redux store. Can be useful for authentication.
*
* @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`
*
*/
export declare function fetchBaseQuery({ baseUrl, prepareHeaders, fetchFn, ...baseFetchOptions }?: FetchBaseQueryArgs): BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;
export {};

View file

@ -0,0 +1,14 @@
export { QueryStatus } from './core/apiState';
export type { Api, Module, ApiModules } from './apiTypes';
export type { BaseQueryEnhancer, BaseQueryFn } from './baseQueryTypes';
export type { EndpointDefinitions, EndpointDefinition, QueryDefinition, MutationDefinition, } 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, SkipToken } from './core/buildSelectors';
export type { CreateApi, CreateApiOptions } from './createApi';
export { buildCreateApi } from './createApi';
export { fakeBaseQuery } from './fakeBaseQuery';
export { copyWithStructuralSharing } from './utils/copyWithStructuralSharing';
export { createApi, coreModule } from './core';

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

View file

@ -0,0 +1,291 @@
import { useEffect } from 'react';
import { QueryStatus } from '@reduxjs/toolkit/query';
import type { QuerySubState, SubscriptionOptions, QueryKeys } from '@reduxjs/toolkit/dist/query/core/apiState';
import type { EndpointDefinitions, MutationDefinition, QueryDefinition, QueryArgFrom } from '@reduxjs/toolkit/dist/query/endpointDefinitions';
import type { MutationResultSelectorResult, SkipToken } from '@reduxjs/toolkit/dist/query/core/buildSelectors';
import type { QueryActionCreatorResult, MutationActionCreatorResult } from '@reduxjs/toolkit/dist/query/core/buildInitiate';
import type { Api } from '@reduxjs/toolkit/dist/query/apiTypes';
import type { Id, NoInfer, Override } from '@reduxjs/toolkit/dist/query/tsHelpers';
import type { CoreModule, PrefetchOptions } from '@reduxjs/toolkit/dist/query/core/module';
import type { ReactHooksModuleOptions } from './module';
import type { UninitializedValue } from './constants';
export declare const useIsomorphicLayoutEffect: typeof useEffect;
export interface QueryHooks<Definition extends QueryDefinition<any, any, any, any, any>> {
useQuery: UseQuery<Definition>;
useLazyQuery: UseLazyQuery<Definition>;
useQuerySubscription: UseQuerySubscription<Definition>;
useLazyQuerySubscription: UseLazyQuerySubscription<Definition>;
useQueryState: UseQueryState<Definition>;
}
export interface MutationHooks<Definition extends MutationDefinition<any, any, any, any, any>> {
useMutation: UseMutation<Definition>;
}
/**
* A React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
*
* The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already, and the hook will return the data for that query arg once it's available.
*
* This hook combines the functionality of both [`useQueryState`](#usequerystate) and [`useQuerySubscription`](#usequerysubscription) together, and is intended to be used in the majority of situations.
*
* #### Features
*
* - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
export declare type UseQuery<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions & UseQueryStateOptions<D, R>) => UseQueryStateResult<D, R> & ReturnType<UseQuerySubscription<D>>;
interface UseQuerySubscriptionOptions extends SubscriptionOptions {
/**
* Prevents a query from automatically running.
*
* @remarks
* When `skip` is true (or `skipToken` is passed in as `arg`):
*
* - **If the query has cached data:**
* * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
* * The query will have a status of `uninitialized`
* * If `skip: false` is set after skipping the initial load, the cached result will be used
* - **If the query does not have cached data:**
* * The query will have a status of `uninitialized`
* * The query will not exist in the state when viewed with the dev tools
* * The query will not automatically fetch on mount
* * The query will not automatically run when additional components with the same query are added that do run
*
* @example
* ```tsx
* // codeblock-meta title="Skip example"
* const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
* const { data, error, status } = useGetPokemonByNameQuery(name, {
* skip,
* });
*
* return (
* <div>
* {name} - {status}
* </div>
* );
* };
* ```
*/
skip?: boolean;
/**
* Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.
* - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
* - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.
* - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*/
refetchOnMountOrArgChange?: boolean | number;
}
/**
* A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.
*
* The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.
*
* Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).
*
* #### Features
*
* - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
*/
export declare type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions) => Pick<QueryActionCreatorResult<D>, 'refetch'>;
export declare type UseLazyQueryLastPromiseInfo<D extends QueryDefinition<any, any, any, any>> = {
lastArg: QueryArgFrom<D>;
};
/**
* A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.
*
* This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).
*
* #### Features
*
* - Manual control over firing a request to retrieve data
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
*
*/
export declare type UseLazyQuery<D extends QueryDefinition<any, any, any, any>> = <R = UseQueryStateDefaultResult<D>>(options?: SubscriptionOptions & Omit<UseQueryStateOptions<D, R>, 'skip'>) => [
(arg: QueryArgFrom<D>) => void,
UseQueryStateResult<D, R>,
UseLazyQueryLastPromiseInfo<D>
];
/**
* A React hook similar to [`useQuerySubscription`](#usequerysubscription), but with manual control over when the data fetching occurs.
*
* Note that this hook does not return a request status or cached data. For that use-case, see [`useLazyQuery`](#uselazyquery).
*
* #### Features
*
* - Manual control over firing a request to retrieve data
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
*/
export declare type UseLazyQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (options?: SubscriptionOptions) => [(arg: QueryArgFrom<D>) => void, QueryArgFrom<D> | UninitializedValue];
export declare type QueryStateSelector<R extends Record<string, any>, D extends QueryDefinition<any, any, any, any>> = (state: UseQueryStateDefaultResult<D>) => R;
/**
* A React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
*
* Note that this hook does not trigger fetching new data. For that use-case, see [`useQuery`](#usequery) or [`useQuerySubscription`](#usequerysubscription).
*
* #### Features
*
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
export declare type UseQueryState<D extends QueryDefinition<any, any, any, any>> = <R = UseQueryStateDefaultResult<D>>(arg: QueryArgFrom<D> | SkipToken, options?: UseQueryStateOptions<D, R>) => UseQueryStateResult<D, R>;
export declare type UseQueryStateOptions<D extends QueryDefinition<any, any, any, any>, R extends Record<string, any>> = {
/**
* Prevents a query from automatically running.
*
* @remarks
* When skip is true:
*
* - **If the query has cached data:**
* * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
* * The query will have a status of `uninitialized`
* * If `skip: false` is set after skipping the initial load, the cached result will be used
* - **If the query does not have cached data:**
* * The query will have a status of `uninitialized`
* * The query will not exist in the state when viewed with the dev tools
* * The query will not automatically fetch on mount
* * The query will not automatically run when additional components with the same query are added that do run
*
* @example
* ```ts
* // codeblock-meta title="Skip example"
* const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
* const { data, error, status } = useGetPokemonByNameQuery(name, {
* skip,
* });
*
* return (
* <div>
* {name} - {status}
* </div>
* );
* };
* ```
*/
skip?: boolean;
/**
* `selectFromResult` allows you to get a specific segment from a query result in a performant manner.
* When using this feature, the component will not rerender unless the underlying data of the selected item has changed.
* If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
*
* @example
* ```ts
* // codeblock-meta title="Using selectFromResult to extract a single result"
* function PostsList() {
* const { data: posts } = api.useGetPostsQuery();
*
* return (
* <ul>
* {posts?.data?.map((post) => (
* <PostById key={post.id} id={post.id} />
* ))}
* </ul>
* );
* }
*
* function PostById({ id }: { id: number }) {
* // Will select the post with the given id, and will only rerender if the given posts data changes
* const { post } = api.useGetPostsQuery(undefined, {
* selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),
* });
*
* return <li>{post?.name}</li>;
* }
* ```
*/
selectFromResult?: QueryStateSelector<R, D>;
};
export declare type UseQueryStateResult<_ extends QueryDefinition<any, any, any, any>, R> = NoInfer<R>;
declare type UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> = QuerySubState<D> & {
/**
* Query has not started yet.
*/
isUninitialized: false;
/**
* Query is currently loading for the first time. No data yet.
*/
isLoading: false;
/**
* Query is currently fetching, but might have data from an earlier request.
*/
isFetching: false;
/**
* Query has data from a successful load.
*/
isSuccess: false;
/**
* Query is currently in "error" state.
*/
isError: false;
};
declare type UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> = Id<Override<Extract<UseQueryStateBaseResult<D>, {
status: QueryStatus.uninitialized;
}>, {
isUninitialized: true;
}> | Override<UseQueryStateBaseResult<D>, {
isLoading: true;
isFetching: boolean;
data: undefined;
} | ({
isSuccess: true;
isFetching: boolean;
error: undefined;
} & Required<Pick<UseQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp'>>) | ({
isError: true;
} & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>)>> & {
/**
* @deprecated will be removed in the next version
* please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
* and `isUninitialized` flags instead
*/
status: QueryStatus;
};
export declare type MutationStateSelector<R extends Record<string, any>, D extends MutationDefinition<any, any, any, any>> = (state: MutationResultSelectorResult<D>) => R;
export declare type UseMutationStateOptions<D extends MutationDefinition<any, any, any, any>, R extends Record<string, any>> = {
selectFromResult?: MutationStateSelector<R, D>;
};
export declare type UseMutationStateResult<D extends MutationDefinition<any, any, any, any>, R> = NoInfer<R> & {
originalArgs?: QueryArgFrom<D>;
};
/**
* A React hook that lets you trigger an update request for a given endpoint, and subscribes the component to read the request status from the Redux store. The component will re-render as the loading status changes.
*
* #### Features
*
* - Manual control over firing a request to alter data on the server or possibly invalidate the cache
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
export declare type UseMutation<D extends MutationDefinition<any, any, any, any>> = <R extends Record<string, any> = MutationResultSelectorResult<D>>(options?: UseMutationStateOptions<D, R>) => [
(arg: QueryArgFrom<D>) => MutationActionCreatorResult<D>,
UseMutationStateResult<D, R>
];
/**
*
* @param opts.api - An API with defined endpoints to create hooks for
* @param opts.moduleOptions.batch - The version of the `batchedUpdates` function to be used
* @param opts.moduleOptions.useDispatch - The version of the `useDispatch` hook to be used
* @param opts.moduleOptions.useSelector - The version of the `useSelector` hook to be used
* @returns An object containing functions to generate hooks based on an endpoint
*/
export declare function buildHooks<Definitions extends EndpointDefinitions>({ api, moduleOptions: { batch, useDispatch, useSelector, useStore }, }: {
api: Api<any, Definitions, any, any, CoreModule>;
moduleOptions: Required<ReactHooksModuleOptions>;
}): {
buildQueryHooks: (name: string) => QueryHooks<any>;
buildMutationHook: (name: string) => UseMutation<any>;
usePrefetch: <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, defaultOptions?: PrefetchOptions | undefined) => (arg: any, options?: PrefetchOptions | undefined) => void;
};
export {};

View file

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

View file

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

View file

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

View file

@ -0,0 +1,60 @@
import type { MutationHooks, QueryHooks } from './buildHooks';
import type { EndpointDefinitions, QueryDefinition, MutationDefinition, QueryArgFrom } from '@reduxjs/toolkit/dist/query/endpointDefinitions';
import type { Module } from '../apiTypes';
import type { BaseQueryFn } from '@reduxjs/toolkit/dist/query/baseQueryTypes';
import type { HooksWithUniqueNames } from './versionedTypes';
import type { QueryKeys } from '../core/apiState';
import type { PrefetchOptions } from '../core/module';
export declare const reactHooksModuleName: unique symbol;
export declare type ReactHooksModule = typeof reactHooksModuleName;
declare module '@reduxjs/toolkit/dist/query/apiTypes' {
interface ApiModules<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {
[reactHooksModuleName]: {
/**
* Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.
*/
endpoints: {
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? QueryHooks<Definitions[K]> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? MutationHooks<Definitions[K]> : never;
};
/**
* A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.
*/
usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, options?: PrefetchOptions): (arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions) => void;
} & HooksWithUniqueNames<Definitions>;
}
}
declare type RR = typeof import('react-redux');
export interface ReactHooksModuleOptions {
/**
* The version of the `batchedUpdates` function to be used
*/
batch?: RR['batch'];
/**
* The version of the `useDispatch` hook to be used
*/
useDispatch?: RR['useDispatch'];
/**
* The version of the `useSelector` hook to be used
*/
useSelector?: RR['useSelector'];
/**
* The version of the `useStore` hook to be used
*/
useStore?: RR['useStore'];
}
/**
* Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.
*
* @example
* ```ts
* const MyContext = React.createContext<ReactReduxContextValue>(null as any);
* const customCreateApi = buildCreateApi(
* coreModule(),
* reactHooksModule({ useDispatch: createDispatchHook(MyContext) })
* );
* ```
*
* @returns A module for use with `buildCreateApi`
*/
export declare const reactHooksModule: ({ batch, useDispatch, useSelector, useStore, }?: ReactHooksModuleOptions) => Module<ReactHooksModule>;
export {};

View file

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

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

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

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,324 @@
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
// src/query/react/index.ts
import { coreModule, buildCreateApi } from "@reduxjs/toolkit/query";
// src/query/react/buildHooks.ts
import { createSelector } from "@reduxjs/toolkit";
import { useCallback, useEffect as useEffect2, useLayoutEffect, useMemo, useRef as useRef2, useState } from "react";
import { QueryStatus, skipToken } from "@reduxjs/toolkit/query";
import { shallowEqual as shallowEqual2 } from "react-redux";
// src/query/react/useShallowStableValue.ts
import { useEffect, useRef } from "react";
import { shallowEqual } from "react-redux";
function useShallowStableValue(value) {
const cache = useRef(value);
useEffect(() => {
if (!shallowEqual(cache.current, value)) {
cache.current = value;
}
}, [value]);
return shallowEqual(cache.current, value) ? cache.current : value;
}
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/buildHooks.ts
var useIsomorphicLayoutEffect = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined" ? useLayoutEffect : useEffect2;
var defaultQueryStateSelector = (x) => x;
var defaultMutationStateSelector = (x) => x;
var queryStatePreSelector = (currentState, lastResult) => {
var _a;
const data = (_a = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data) != null ? _a : currentState.data;
const isFetching = currentState.isLoading;
const isLoading = !data && isFetching;
const isSuccess = currentState.isSuccess || isFetching && !!data;
return __spreadProps(__spreadValues({}, currentState), {
data,
isFetching,
isLoading,
isSuccess
});
};
var noPendingQueryStateSelector = (selected) => {
if (selected.isUninitialized) {
return __spreadProps(__spreadValues({}, selected), {
isUninitialized: false,
isFetching: true,
isLoading: true,
status: QueryStatus.pending
});
}
return selected;
};
function buildHooks({ api, moduleOptions: { batch, useDispatch, useSelector, useStore } }) {
return { buildQueryHooks, buildMutationHook, usePrefetch };
function usePrefetch(endpointName, defaultOptions) {
const dispatch = useDispatch();
const stableDefaultOptions = useShallowStableValue(defaultOptions);
return useCallback((arg, options) => dispatch(api.util.prefetch(endpointName, arg, __spreadValues(__spreadValues({}, stableDefaultOptions), options))), [endpointName, dispatch, stableDefaultOptions]);
}
function buildQueryHooks(name) {
const useQuerySubscription = (arg, { refetchOnReconnect, refetchOnFocus, refetchOnMountOrArgChange, skip = false, pollingInterval = 0 } = {}) => {
const { initiate } = api.endpoints[name];
const dispatch = useDispatch();
const stableArg = useShallowStableValue(skip ? skipToken : arg);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval
});
const promiseRef = useRef2();
useEffect2(() => {
var _a;
const lastPromise = promiseRef.current;
if (stableArg === skipToken) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
promiseRef.current = void 0;
return;
}
const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (!lastPromise || lastPromise.arg !== stableArg) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
const promise = dispatch(initiate(stableArg, {
subscriptionOptions: stableSubscriptionOptions,
forceRefetch: refetchOnMountOrArgChange
}));
promiseRef.current = promise;
}
else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [
dispatch,
initiate,
refetchOnMountOrArgChange,
stableArg,
stableSubscriptionOptions
]);
useEffect2(() => {
return () => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return useMemo(() => ({
refetch: () => {
var _a;
return void ((_a = promiseRef.current) == null ? void 0 : _a.refetch());
}
}), []);
};
const useLazyQuerySubscription = ({ refetchOnReconnect, refetchOnFocus, pollingInterval = 0 } = {}) => {
const { initiate } = api.endpoints[name];
const dispatch = useDispatch();
const [arg, setArg] = useState(UNINITIALIZED_VALUE);
const promiseRef = useRef2();
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval
});
useEffect2(() => {
var _a, _b;
const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (stableSubscriptionOptions !== lastSubscriptionOptions) {
(_b = promiseRef.current) == null ? void 0 : _b.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [stableSubscriptionOptions]);
const subscriptionOptionsRef = useRef2(stableSubscriptionOptions);
useEffect2(() => {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
const trigger = useCallback(function (arg2, preferCacheValue = false) {
batch(() => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
}, [dispatch, initiate]);
useEffect2(() => {
return () => {
var _a;
(_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
};
}, []);
useEffect2(() => {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return useMemo(() => [trigger, arg], [trigger, arg]);
};
const useQueryState = (arg, { skip = false, selectFromResult = defaultQueryStateSelector } = {}) => {
const { select } = api.endpoints[name];
const stableArg = useShallowStableValue(skip ? skipToken : arg);
const lastValue = useRef2();
const selectDefaultResult = useMemo(() => createSelector([select(stableArg), (_, lastResult) => lastResult], queryStatePreSelector), [select, stableArg]);
const querySelector = useMemo(() => createSelector([selectDefaultResult], selectFromResult), [selectDefaultResult, selectFromResult]);
const currentState = useSelector((state) => querySelector(state, lastValue.current), shallowEqual2);
const store = useStore();
const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
useIsomorphicLayoutEffect(() => {
lastValue.current = newLastValue;
}, [newLastValue]);
return currentState;
};
return {
useQueryState,
useQuerySubscription,
useLazyQuerySubscription,
useLazyQuery(options) {
const [trigger, arg] = useLazyQuerySubscription(options);
const queryStateResults = useQueryState(arg, __spreadProps(__spreadValues({}, options), {
skip: arg === UNINITIALIZED_VALUE
}));
const info = useMemo(() => ({ lastArg: arg }), [arg]);
return useMemo(() => [trigger, queryStateResults, info], [trigger, queryStateResults, info]);
},
useQuery(arg, options) {
const querySubscriptionResults = useQuerySubscription(arg, options);
const queryStateResults = useQueryState(arg, __spreadValues({
selectFromResult: arg === skipToken || (options == null ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector
}, options));
return useMemo(() => __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults), [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return ({ selectFromResult = defaultMutationStateSelector } = {}) => {
var _a;
const { select, initiate } = api.endpoints[name];
const dispatch = useDispatch();
const [requestId, setRequestId] = useState();
const promiseRef = useRef2();
useEffect2(() => {
return () => {
var _a2;
(_a2 = promiseRef.current) == null ? void 0 : _a2.unsubscribe();
promiseRef.current = void 0;
};
}, []);
const triggerMutation = useCallback(function (arg) {
let promise;
batch(() => {
var _a2;
(_a2 = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a2.unsubscribe();
promise = dispatch(initiate(arg));
promiseRef.current = promise;
setRequestId(promise.requestId);
});
return promise;
}, [dispatch, initiate]);
const mutationSelector = useMemo(() => createSelector([select(requestId || skipToken)], (subState) => selectFromResult(subState)), [select, requestId, selectFromResult]);
const currentState = useSelector(mutationSelector, shallowEqual2);
const originalArgs = (_a = promiseRef.current) == null ? void 0 : _a.arg.originalArgs;
const finalState = useMemo(() => __spreadProps(__spreadValues({}, currentState), {
originalArgs
}), [currentState, originalArgs]);
return useMemo(() => [triggerMutation, finalState], [triggerMutation, finalState]);
};
}
}
// src/query/endpointDefinitions.ts
var DefinitionType;
(function (DefinitionType2) {
DefinitionType2["query"] = "query";
DefinitionType2["mutation"] = "mutation";
})(DefinitionType || (DefinitionType = {}));
function isQueryDefinition(e) {
return e.type === DefinitionType.query;
}
function isMutationDefinition(e) {
return e.type === DefinitionType.mutation;
}
// src/query/utils/capitalize.ts
function capitalize(str) {
return str.replace(str[0], str[0].toUpperCase());
}
// src/query/tsHelpers.ts
function safeAssign(target, ...args) {
Object.assign(target, ...args);
}
// src/query/react/module.ts
import { useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore, batch as rrBatch } from "react-redux";
var reactHooksModuleName = /* @__PURE__ */ Symbol();
var reactHooksModule = ({ batch = rrBatch, useDispatch = rrUseDispatch, useSelector = rrUseSelector, useStore = rrUseStore } = {}) => ({
name: reactHooksModuleName,
init(api, options, context) {
const anyApi = api;
const { buildQueryHooks, buildMutationHook, usePrefetch } = buildHooks({
api,
moduleOptions: { batch, useDispatch, useSelector, useStore }
});
safeAssign(anyApi, { usePrefetch });
safeAssign(context, { batch });
return {
injectEndpoint(endpointName, definition) {
if (isQueryDefinition(definition)) {
const { useQuery, useLazyQuery, useLazyQuerySubscription, useQueryState, useQuerySubscription } = buildQueryHooks(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription
});
api[`use${capitalize(endpointName)}Query`] = useQuery;
api[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;
}
else if (isMutationDefinition(definition)) {
const useMutation = buildMutationHook(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useMutation
});
api[`use${capitalize(endpointName)}Mutation`] = useMutation;
}
}
};
}
});
// src/query/react/index.ts
export * from "@reduxjs/toolkit/query";
// src/query/react/ApiProvider.tsx
import { configureStore } from "@reduxjs/toolkit";
import React from "react";
import { Provider } from "react-redux";
import { setupListeners } from "@reduxjs/toolkit/query";
function ApiProvider(props) {
const [store] = React.useState(() => configureStore({
reducer: {
[props.api.reducerPath]: props.api.reducer
},
middleware: (gDM) => gDM().concat(props.api.middleware)
}));
setupListeners(store.dispatch, props.setupListeners);
return /* @__PURE__ */ React.createElement(Provider, {
store,
context: props.context
}, props.children);
}
// src/query/react/index.ts
var createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule());
export { ApiProvider, createApi, reactHooksModule };
//# sourceMappingURL=module.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,324 @@
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
// src/query/react/index.ts
import { coreModule, buildCreateApi } from "@reduxjs/toolkit/query";
// src/query/react/buildHooks.ts
import { createSelector } from "@reduxjs/toolkit";
import { useCallback, useEffect as useEffect2, useLayoutEffect, useMemo, useRef as useRef2, useState } from "react";
import { QueryStatus, skipToken } from "@reduxjs/toolkit/query";
import { shallowEqual as shallowEqual2 } from "react-redux";
// src/query/react/useShallowStableValue.ts
import { useEffect, useRef } from "react";
import { shallowEqual } from "react-redux";
function useShallowStableValue(value) {
const cache = useRef(value);
useEffect(() => {
if (!shallowEqual(cache.current, value)) {
cache.current = value;
}
}, [value]);
return shallowEqual(cache.current, value) ? cache.current : value;
}
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/buildHooks.ts
var useIsomorphicLayoutEffect = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined" ? useLayoutEffect : useEffect2;
var defaultQueryStateSelector = (x) => x;
var defaultMutationStateSelector = (x) => x;
var queryStatePreSelector = (currentState, lastResult) => {
var _a;
const data = (_a = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data) != null ? _a : currentState.data;
const isFetching = currentState.isLoading;
const isLoading = !data && isFetching;
const isSuccess = currentState.isSuccess || isFetching && !!data;
return __spreadProps(__spreadValues({}, currentState), {
data,
isFetching,
isLoading,
isSuccess
});
};
var noPendingQueryStateSelector = (selected) => {
if (selected.isUninitialized) {
return __spreadProps(__spreadValues({}, selected), {
isUninitialized: false,
isFetching: true,
isLoading: true,
status: QueryStatus.pending
});
}
return selected;
};
function buildHooks({ api, moduleOptions: { batch, useDispatch, useSelector, useStore } }) {
return { buildQueryHooks, buildMutationHook, usePrefetch };
function usePrefetch(endpointName, defaultOptions) {
const dispatch = useDispatch();
const stableDefaultOptions = useShallowStableValue(defaultOptions);
return useCallback((arg, options) => dispatch(api.util.prefetch(endpointName, arg, __spreadValues(__spreadValues({}, stableDefaultOptions), options))), [endpointName, dispatch, stableDefaultOptions]);
}
function buildQueryHooks(name) {
const useQuerySubscription = (arg, { refetchOnReconnect, refetchOnFocus, refetchOnMountOrArgChange, skip = false, pollingInterval = 0 } = {}) => {
const { initiate } = api.endpoints[name];
const dispatch = useDispatch();
const stableArg = useShallowStableValue(skip ? skipToken : arg);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval
});
const promiseRef = useRef2();
useEffect2(() => {
var _a;
const lastPromise = promiseRef.current;
if (stableArg === skipToken) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
promiseRef.current = void 0;
return;
}
const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (!lastPromise || lastPromise.arg !== stableArg) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
const promise = dispatch(initiate(stableArg, {
subscriptionOptions: stableSubscriptionOptions,
forceRefetch: refetchOnMountOrArgChange
}));
promiseRef.current = promise;
}
else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [
dispatch,
initiate,
refetchOnMountOrArgChange,
stableArg,
stableSubscriptionOptions
]);
useEffect2(() => {
return () => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return useMemo(() => ({
refetch: () => {
var _a;
return void ((_a = promiseRef.current) == null ? void 0 : _a.refetch());
}
}), []);
};
const useLazyQuerySubscription = ({ refetchOnReconnect, refetchOnFocus, pollingInterval = 0 } = {}) => {
const { initiate } = api.endpoints[name];
const dispatch = useDispatch();
const [arg, setArg] = useState(UNINITIALIZED_VALUE);
const promiseRef = useRef2();
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval
});
useEffect2(() => {
var _a, _b;
const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (stableSubscriptionOptions !== lastSubscriptionOptions) {
(_b = promiseRef.current) == null ? void 0 : _b.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [stableSubscriptionOptions]);
const subscriptionOptionsRef = useRef2(stableSubscriptionOptions);
useEffect2(() => {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
const trigger = useCallback(function (arg2, preferCacheValue = false) {
batch(() => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
}, [dispatch, initiate]);
useEffect2(() => {
return () => {
var _a;
(_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
};
}, []);
useEffect2(() => {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return useMemo(() => [trigger, arg], [trigger, arg]);
};
const useQueryState = (arg, { skip = false, selectFromResult = defaultQueryStateSelector } = {}) => {
const { select } = api.endpoints[name];
const stableArg = useShallowStableValue(skip ? skipToken : arg);
const lastValue = useRef2();
const selectDefaultResult = useMemo(() => createSelector([select(stableArg), (_, lastResult) => lastResult], queryStatePreSelector), [select, stableArg]);
const querySelector = useMemo(() => createSelector([selectDefaultResult], selectFromResult), [selectDefaultResult, selectFromResult]);
const currentState = useSelector((state) => querySelector(state, lastValue.current), shallowEqual2);
const store = useStore();
const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
useIsomorphicLayoutEffect(() => {
lastValue.current = newLastValue;
}, [newLastValue]);
return currentState;
};
return {
useQueryState,
useQuerySubscription,
useLazyQuerySubscription,
useLazyQuery(options) {
const [trigger, arg] = useLazyQuerySubscription(options);
const queryStateResults = useQueryState(arg, __spreadProps(__spreadValues({}, options), {
skip: arg === UNINITIALIZED_VALUE
}));
const info = useMemo(() => ({ lastArg: arg }), [arg]);
return useMemo(() => [trigger, queryStateResults, info], [trigger, queryStateResults, info]);
},
useQuery(arg, options) {
const querySubscriptionResults = useQuerySubscription(arg, options);
const queryStateResults = useQueryState(arg, __spreadValues({
selectFromResult: arg === skipToken || (options == null ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector
}, options));
return useMemo(() => __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults), [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return ({ selectFromResult = defaultMutationStateSelector } = {}) => {
var _a;
const { select, initiate } = api.endpoints[name];
const dispatch = useDispatch();
const [requestId, setRequestId] = useState();
const promiseRef = useRef2();
useEffect2(() => {
return () => {
var _a2;
(_a2 = promiseRef.current) == null ? void 0 : _a2.unsubscribe();
promiseRef.current = void 0;
};
}, []);
const triggerMutation = useCallback(function (arg) {
let promise;
batch(() => {
var _a2;
(_a2 = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a2.unsubscribe();
promise = dispatch(initiate(arg));
promiseRef.current = promise;
setRequestId(promise.requestId);
});
return promise;
}, [dispatch, initiate]);
const mutationSelector = useMemo(() => createSelector([select(requestId || skipToken)], (subState) => selectFromResult(subState)), [select, requestId, selectFromResult]);
const currentState = useSelector(mutationSelector, shallowEqual2);
const originalArgs = (_a = promiseRef.current) == null ? void 0 : _a.arg.originalArgs;
const finalState = useMemo(() => __spreadProps(__spreadValues({}, currentState), {
originalArgs
}), [currentState, originalArgs]);
return useMemo(() => [triggerMutation, finalState], [triggerMutation, finalState]);
};
}
}
// src/query/endpointDefinitions.ts
var DefinitionType;
(function (DefinitionType2) {
DefinitionType2["query"] = "query";
DefinitionType2["mutation"] = "mutation";
})(DefinitionType || (DefinitionType = {}));
function isQueryDefinition(e) {
return e.type === DefinitionType.query;
}
function isMutationDefinition(e) {
return e.type === DefinitionType.mutation;
}
// src/query/utils/capitalize.ts
function capitalize(str) {
return str.replace(str[0], str[0].toUpperCase());
}
// src/query/tsHelpers.ts
function safeAssign(target, ...args) {
Object.assign(target, ...args);
}
// src/query/react/module.ts
import { useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore, batch as rrBatch } from "react-redux";
var reactHooksModuleName = /* @__PURE__ */ Symbol();
var reactHooksModule = ({ batch = rrBatch, useDispatch = rrUseDispatch, useSelector = rrUseSelector, useStore = rrUseStore } = {}) => ({
name: reactHooksModuleName,
init(api, options, context) {
const anyApi = api;
const { buildQueryHooks, buildMutationHook, usePrefetch } = buildHooks({
api,
moduleOptions: { batch, useDispatch, useSelector, useStore }
});
safeAssign(anyApi, { usePrefetch });
safeAssign(context, { batch });
return {
injectEndpoint(endpointName, definition) {
if (isQueryDefinition(definition)) {
const { useQuery, useLazyQuery, useLazyQuerySubscription, useQueryState, useQuerySubscription } = buildQueryHooks(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription
});
api[`use${capitalize(endpointName)}Query`] = useQuery;
api[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;
}
else if (isMutationDefinition(definition)) {
const useMutation = buildMutationHook(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useMutation
});
api[`use${capitalize(endpointName)}Mutation`] = useMutation;
}
}
};
}
});
// src/query/react/index.ts
export * from "@reduxjs/toolkit/query";
// src/query/react/ApiProvider.tsx
import { configureStore } from "@reduxjs/toolkit";
import React from "react";
import { Provider } from "react-redux";
import { setupListeners } from "@reduxjs/toolkit/query";
function ApiProvider(props) {
const [store] = React.useState(() => configureStore({
reducer: {
[props.api.reducerPath]: props.api.reducer
},
middleware: (gDM) => gDM().concat(props.api.middleware)
}));
setupListeners(store.dispatch, props.setupListeners);
return /* @__PURE__ */ React.createElement(Provider, {
store,
context: props.context
}, props.children);
}
// src/query/react/index.ts
var createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule());
export { ApiProvider, createApi, reactHooksModule };
//# sourceMappingURL=module.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,48 @@
import type { BaseQueryEnhancer } from './baseQueryTypes';
interface StaggerOptions {
/**
* How many times the query will be retried (default: 5)
*/
maxRetries?: number;
/**
* Function used to determine delay between retries
*/
backoff?: (attempt: number, maxRetries: number) => Promise<void>;
}
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, StaggerOptions, void | StaggerOptions> & {
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

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

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,22 @@
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 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,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;