source: node_modules/@reduxjs/toolkit/src/query/react/module.ts@ a762898

Last change on this file since a762898 was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago

Added visualizations

  • Property mode set to 100644
File size: 7.9 KB
Line 
1import type {
2 Api,
3 BaseQueryFn,
4 EndpointDefinitions,
5 InfiniteQueryDefinition,
6 Module,
7 MutationDefinition,
8 PrefetchOptions,
9 QueryArgFrom,
10 QueryDefinition,
11 QueryKeys,
12} from '@reduxjs/toolkit/query'
13import {
14 batch as rrBatch,
15 useDispatch as rrUseDispatch,
16 useSelector as rrUseSelector,
17 useStore as rrUseStore,
18} from 'react-redux'
19import type { CreateSelectorFunction } from 'reselect'
20import { createSelector as _createSelector } from 'reselect'
21import {
22 isInfiniteQueryDefinition,
23 isMutationDefinition,
24 isQueryDefinition,
25} from '../endpointDefinitions'
26import { safeAssign } from '../tsHelpers'
27import { capitalize, countObjectKeys } from '../utils'
28import type {
29 InfiniteQueryHooks,
30 MutationHooks,
31 QueryHooks,
32} from './buildHooks'
33import { buildHooks } from './buildHooks'
34import type { HooksWithUniqueNames } from './namedHooks'
35
36export const reactHooksModuleName = /* @__PURE__ */ Symbol()
37export type ReactHooksModule = typeof reactHooksModuleName
38
39declare module '@reduxjs/toolkit/query' {
40 export interface ApiModules<
41 // eslint-disable-next-line @typescript-eslint/no-unused-vars
42 BaseQuery extends BaseQueryFn,
43 Definitions extends EndpointDefinitions,
44 // eslint-disable-next-line @typescript-eslint/no-unused-vars
45 ReducerPath extends string,
46 // eslint-disable-next-line @typescript-eslint/no-unused-vars
47 TagTypes extends string,
48 > {
49 [reactHooksModuleName]: {
50 /**
51 * Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.
52 */
53 endpoints: {
54 [K in keyof Definitions]: Definitions[K] extends QueryDefinition<
55 any,
56 any,
57 any,
58 any,
59 any
60 >
61 ? QueryHooks<Definitions[K]>
62 : Definitions[K] extends MutationDefinition<any, any, any, any, any>
63 ? MutationHooks<Definitions[K]>
64 : Definitions[K] extends InfiniteQueryDefinition<
65 any,
66 any,
67 any,
68 any,
69 any
70 >
71 ? InfiniteQueryHooks<Definitions[K]>
72 : never
73 }
74 /**
75 * A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.
76 */
77 usePrefetch<EndpointName extends QueryKeys<Definitions>>(
78 endpointName: EndpointName,
79 options?: PrefetchOptions,
80 ): (
81 arg: QueryArgFrom<Definitions[EndpointName]>,
82 options?: PrefetchOptions,
83 ) => void
84 } & HooksWithUniqueNames<Definitions>
85 }
86}
87
88type RR = typeof import('react-redux')
89
90export interface ReactHooksModuleOptions {
91 /**
92 * The hooks from React Redux to be used
93 */
94 hooks?: {
95 /**
96 * The version of the `useDispatch` hook to be used
97 */
98 useDispatch: RR['useDispatch']
99 /**
100 * The version of the `useSelector` hook to be used
101 */
102 useSelector: RR['useSelector']
103 /**
104 * The version of the `useStore` hook to be used
105 */
106 useStore: RR['useStore']
107 }
108 /**
109 * The version of the `batchedUpdates` function to be used
110 */
111 batch?: RR['batch']
112 /**
113 * Enables performing asynchronous tasks immediately within a render.
114 *
115 * @example
116 *
117 * ```ts
118 * import {
119 * buildCreateApi,
120 * coreModule,
121 * reactHooksModule
122 * } from '@reduxjs/toolkit/query/react'
123 *
124 * const createApi = buildCreateApi(
125 * coreModule(),
126 * reactHooksModule({ unstable__sideEffectsInRender: true })
127 * )
128 * ```
129 */
130 unstable__sideEffectsInRender?: boolean
131 /**
132 * A selector creator (usually from `reselect`, or matching the same signature)
133 */
134 createSelector?: CreateSelectorFunction<any, any, any>
135}
136
137/**
138 * Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.
139 *
140 * @example
141 * ```ts
142 * const MyContext = React.createContext<ReactReduxContextValue | null>(null);
143 * const customCreateApi = buildCreateApi(
144 * coreModule(),
145 * reactHooksModule({
146 * hooks: {
147 * useDispatch: createDispatchHook(MyContext),
148 * useSelector: createSelectorHook(MyContext),
149 * useStore: createStoreHook(MyContext)
150 * }
151 * })
152 * );
153 * ```
154 *
155 * @returns A module for use with `buildCreateApi`
156 */
157export const reactHooksModule = ({
158 batch = rrBatch,
159 hooks = {
160 useDispatch: rrUseDispatch,
161 useSelector: rrUseSelector,
162 useStore: rrUseStore,
163 },
164 createSelector = _createSelector,
165 unstable__sideEffectsInRender = false,
166 ...rest
167}: ReactHooksModuleOptions = {}): Module<ReactHooksModule> => {
168 if (process.env.NODE_ENV !== 'production') {
169 const hookNames = ['useDispatch', 'useSelector', 'useStore'] as const
170 let warned = false
171 for (const hookName of hookNames) {
172 // warn for old hook options
173 if (countObjectKeys(rest) > 0) {
174 if ((rest as Partial<typeof hooks>)[hookName]) {
175 if (!warned) {
176 console.warn(
177 'As of RTK 2.0, the hooks now need to be specified as one object, provided under a `hooks` key:' +
178 '\n`reactHooksModule({ hooks: { useDispatch, useSelector, useStore } })`',
179 )
180 warned = true
181 }
182 }
183 // migrate
184 // @ts-ignore
185 hooks[hookName] = rest[hookName]
186 }
187 // then make sure we have them all
188 if (typeof hooks[hookName] !== 'function') {
189 throw new Error(
190 `When using custom hooks for context, all ${
191 hookNames.length
192 } hooks need to be provided: ${hookNames.join(
193 ', ',
194 )}.\nHook ${hookName} was either not provided or not a function.`,
195 )
196 }
197 }
198 }
199
200 return {
201 name: reactHooksModuleName,
202 init(api, { serializeQueryArgs }, context) {
203 const anyApi = api as any as Api<
204 any,
205 Record<string, any>,
206 any,
207 any,
208 ReactHooksModule
209 >
210 const {
211 buildQueryHooks,
212 buildInfiniteQueryHooks,
213 buildMutationHook,
214 usePrefetch,
215 } = buildHooks({
216 api,
217 moduleOptions: {
218 batch,
219 hooks,
220 unstable__sideEffectsInRender,
221 createSelector,
222 },
223 serializeQueryArgs,
224 context,
225 })
226 safeAssign(anyApi, { usePrefetch })
227 safeAssign(context, { batch })
228
229 return {
230 injectEndpoint(endpointName, definition) {
231 if (isQueryDefinition(definition)) {
232 const {
233 useQuery,
234 useLazyQuery,
235 useLazyQuerySubscription,
236 useQueryState,
237 useQuerySubscription,
238 } = buildQueryHooks(endpointName)
239 safeAssign(anyApi.endpoints[endpointName], {
240 useQuery,
241 useLazyQuery,
242 useLazyQuerySubscription,
243 useQueryState,
244 useQuerySubscription,
245 })
246 ;(api as any)[`use${capitalize(endpointName)}Query`] = useQuery
247 ;(api as any)[`useLazy${capitalize(endpointName)}Query`] =
248 useLazyQuery
249 }
250 if (isMutationDefinition(definition)) {
251 const useMutation = buildMutationHook(endpointName)
252 safeAssign(anyApi.endpoints[endpointName], {
253 useMutation,
254 })
255 ;(api as any)[`use${capitalize(endpointName)}Mutation`] =
256 useMutation
257 } else if (isInfiniteQueryDefinition(definition)) {
258 const {
259 useInfiniteQuery,
260 useInfiniteQuerySubscription,
261 useInfiniteQueryState,
262 } = buildInfiniteQueryHooks(endpointName)
263 safeAssign(anyApi.endpoints[endpointName], {
264 useInfiniteQuery,
265 useInfiniteQuerySubscription,
266 useInfiniteQueryState,
267 })
268 ;(api as any)[`use${capitalize(endpointName)}InfiniteQuery`] =
269 useInfiniteQuery
270 }
271 },
272 }
273 },
274 }
275}
Note: See TracBrowser for help on using the repository browser.