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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
import type {
  Selector,
  ThunkAction,
  ThunkDispatch,
  UnknownAction,
} from '@reduxjs/toolkit'
import type {
  Api,
  ApiContext,
  ApiEndpointInfiniteQuery,
  ApiEndpointMutation,
  ApiEndpointQuery,
  BaseQueryFn,
  CoreModule,
  EndpointDefinitions,
  InfiniteQueryActionCreatorResult,
  InfiniteQueryArgFrom,
  InfiniteQueryDefinition,
  InfiniteQueryResultSelectorResult,
  InfiniteQuerySubState,
  MutationActionCreatorResult,
  MutationDefinition,
  MutationResultSelectorResult,
  PageParamFrom,
  PrefetchOptions,
  QueryActionCreatorResult,
  QueryArgFrom,
  QueryCacheKey,
  QueryDefinition,
  QueryKeys,
  QueryResultSelectorResult,
  QuerySubState,
  ResultTypeFrom,
  RootState,
  SerializeQueryArgs,
  SkipToken,
  SubscriptionOptions,
  TSHelpersId,
  TSHelpersNoInfer,
  TSHelpersOverride,
} from '@reduxjs/toolkit/query'
import { QueryStatus, skipToken } from './rtkqImports'
import type { DependencyList } from 'react'
import {
  useCallback,
  useDebugValue,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from './reactImports'
import { shallowEqual } from './reactReduxImports'

import type { SubscriptionSelectors } from '../core/buildMiddleware/index'
import type { InfiniteData, InfiniteQueryConfigOptions } from '../core/index'
import type { UninitializedValue } from './constants'
import { UNINITIALIZED_VALUE } from './constants'
import type { ReactHooksModuleOptions } from './module'
import { useStableQueryArgs } from './useSerializedStableValue'
import { useShallowStableValue } from './useShallowStableValue'
import type { InfiniteQueryDirection } from '../core/apiState'
import { isInfiniteQueryDefinition } from '../endpointDefinitions'
import type { StartInfiniteQueryActionCreator } from '../core/buildInitiate'

// Copy-pasted from React-Redux
const canUseDOM = () =>
  !!(
    typeof window !== 'undefined' &&
    typeof window.document !== 'undefined' &&
    typeof window.document.createElement !== 'undefined'
  )

const isDOM = /* @__PURE__ */ canUseDOM()

// Under React Native, we know that we always want to use useLayoutEffect

const isRunningInReactNative = () =>
  typeof navigator !== 'undefined' && navigator.product === 'ReactNative'

const isReactNative = /* @__PURE__ */ isRunningInReactNative()

const getUseIsomorphicLayoutEffect = () =>
  isDOM || isReactNative ? useLayoutEffect : useEffect

export const useIsomorphicLayoutEffect =
  /* @__PURE__ */ getUseIsomorphicLayoutEffect()

export type 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 type InfiniteQueryHooks<
  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
> = {
  useInfiniteQuery: UseInfiniteQuery<Definition>
  useInfiniteQuerySubscription: UseInfiniteQuerySubscription<Definition>
  useInfiniteQueryState: UseInfiniteQueryState<Definition>
}

export type 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 type UseQuery<D extends QueryDefinition<any, any, any, any>> = <
  R extends Record<string, any> = UseQueryStateDefaultResult<D>,
>(
  arg: QueryArgFrom<D> | SkipToken,
  options?: UseQuerySubscriptionOptions & UseQueryStateOptions<D, R>,
) => UseQueryHookResult<D, R>

export type TypedUseQuery<
  ResultType,
  QueryArg,
  BaseQuery extends BaseQueryFn,
> = UseQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>

export type UseQueryHookResult<
  D extends QueryDefinition<any, any, any, any>,
  R = UseQueryStateDefaultResult<D>,
> = UseQueryStateResult<D, R> & UseQuerySubscriptionResult<D>

/**
 * Helper type to manually type the result
 * of the `useQuery` hook in userland code.
 */
export type TypedUseQueryHookResult<
  ResultType,
  QueryArg,
  BaseQuery extends BaseQueryFn,
  R = UseQueryStateDefaultResult<
    QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
  >,
> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> &
  TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>

export type UseQuerySubscriptionOptions = SubscriptionOptions & {
  /**
   * Prevents a query from automatically running.
   *
   * @remarks
   * When `skip` is true (or `skipToken` is passed in as `arg`):
   *
   * - **If the query has cached data:**
   *   * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
   *   * The query will have a status of `uninitialized`
   *   * If `skip: false` is set after the initial load, the cached result will be used
   * - **If the query does not have cached data:**
   *   * The query will have a status of `uninitialized`
   *   * The query will not exist in the state when viewed with the dev tools
   *   * The query will not automatically fetch on mount
   *   * The query will not automatically run when additional components with the same query are added that do run
   *
   * @example
   * ```tsx
   * // codeblock-meta no-transpile title="Skip example"
   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
   *   const { data, error, status } = useGetPokemonByNameQuery(name, {
   *     skip,
   *   });
   *
   *   return (
   *     <div>
   *       {name} - {status}
   *     </div>
   *   );
   * };
   * ```
   */
  skip?: boolean
  /**
   * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.
   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.
   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.
   *
   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
   */
  refetchOnMountOrArgChange?: boolean | number
}

/**
 * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.
 *
 * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.
 *
 * Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).
 *
 * #### Features
 *
 * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
 * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
 * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
 */
export type UseQuerySubscription<
  D extends QueryDefinition<any, any, any, any>,
> = (
  arg: QueryArgFrom<D> | SkipToken,
  options?: UseQuerySubscriptionOptions,
) => UseQuerySubscriptionResult<D>

export type TypedUseQuerySubscription<
  ResultType,
  QueryArg,
  BaseQuery extends BaseQueryFn,
> = UseQuerySubscription<
  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
>

export type UseQuerySubscriptionResult<
  D extends QueryDefinition<any, any, any, any>,
> = Pick<QueryActionCreatorResult<D>, 'refetch'>

/**
 * Helper type to manually type the result
 * of the `useQuerySubscription` hook in userland code.
 */
export type TypedUseQuerySubscriptionResult<
  ResultType,
  QueryArg,
  BaseQuery extends BaseQueryFn,
> = UseQuerySubscriptionResult<
  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
>

export type UseLazyQueryLastPromiseInfo<
  D extends QueryDefinition<any, any, any, any>,
> = {
  lastArg: QueryArgFrom<D>
}

/**
 * A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.
 *
 * This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).
 *
 * #### Features
 *
 * - Manual control over firing a request to retrieve data
 * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
 * - Returns the latest request status and cached data from the Redux store
 * - Re-renders as the request status changes and data becomes available
 * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
 *
 * #### Note
 *
 * When the trigger function returned from a LazyQuery is called, it always initiates a new request to the server even if there is cached data. Set `preferCacheValue`(the second argument to the function) as `true` if you want it to immediately return a cached value if one exists.
 */
export type UseLazyQuery<D extends QueryDefinition<any, any, any, any>> = <
  R extends Record<string, any> = UseQueryStateDefaultResult<D>,
>(
  options?: SubscriptionOptions & Omit<UseQueryStateOptions<D, R>, 'skip'>,
) => [
  LazyQueryTrigger<D>,
  UseLazyQueryStateResult<D, R>,
  UseLazyQueryLastPromiseInfo<D>,
]

export type TypedUseLazyQuery<
  ResultType,
  QueryArg,
  BaseQuery extends BaseQueryFn,
> = UseLazyQuery<
  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
>

export type UseLazyQueryStateResult<
  D extends QueryDefinition<any, any, any, any>,
  R = UseQueryStateDefaultResult<D>,
> = UseQueryStateResult<D, R> & {
  /**
   * Resets the hook state to its initial `uninitialized` state.
   * This will also remove the last result from the cache.
   */
  reset: () => void
}

/**
 * Helper type to manually type the result
 * of the `useLazyQuery` hook in userland code.
 */
export type TypedUseLazyQueryStateResult<
  ResultType,
  QueryArg,
  BaseQuery extends BaseQueryFn,
  R = UseQueryStateDefaultResult<
    QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
  >,
> = UseLazyQueryStateResult<
  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>,
  R
>

export type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {
  /**
   * Triggers a lazy query.
   *
   * By default, this will start a new request even if there is already a value in the cache.
   * If you want to use the cache value and only start a request if there is no cache value, set the second argument to `true`.
   *
   * @remarks
   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().
   *
   * @example
   * ```ts
   * // codeblock-meta title="Using .unwrap with async await"
   * try {
   *   const payload = await getUserById(1).unwrap();
   *   console.log('fulfilled', payload)
   * } catch (error) {
   *   console.error('rejected', error);
   * }
   * ```
   */
  (
    arg: QueryArgFrom<D>,
    preferCacheValue?: boolean,
  ): QueryActionCreatorResult<D>
}

export type TypedLazyQueryTrigger<
  ResultType,
  QueryArg,
  BaseQuery extends BaseQueryFn,
> = LazyQueryTrigger<
  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
>

/**
 * 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 type UseLazyQuerySubscription<
  D extends QueryDefinition<any, any, any, any>,
> = (
  options?: SubscriptionOptions,
) => readonly [
  LazyQueryTrigger<D>,
  QueryArgFrom<D> | UninitializedValue,
  { reset: () => void },
]

export type TypedUseLazyQuerySubscription<
  ResultType,
  QueryArg,
  BaseQuery extends BaseQueryFn,
> = UseLazyQuerySubscription<
  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
>

/**
 * @internal
 */
export type QueryStateSelector<
  R extends Record<string, any>,
  D extends QueryDefinition<any, any, any, any>,
> = (state: UseQueryStateDefaultResult<D>) => R

/**
 * Provides a way to define a strongly-typed version of
 * {@linkcode QueryStateSelector} for use with a specific query.
 * This is useful for scenarios where you want to create a "pre-typed"
 * {@linkcode UseQueryStateOptions.selectFromResult | selectFromResult}
 * function.
 *
 * @example
 * <caption>#### __Create a strongly-typed `selectFromResult` selector function__</caption>
 *
 * ```tsx
 * import type { TypedQueryStateSelector } from '@reduxjs/toolkit/query/react'
 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
 *
 * type Post = {
 *   id: number
 *   title: string
 * }
 *
 * type PostsApiResponse = {
 *   posts: Post[]
 *   total: number
 *   skip: number
 *   limit: number
 * }
 *
 * type QueryArgument = number | undefined
 *
 * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
 *
 * type SelectedResult = Pick<PostsApiResponse, 'posts'>
 *
 * const postsApiSlice = createApi({
 *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),
 *   reducerPath: 'postsApi',
 *   tagTypes: ['Posts'],
 *   endpoints: (build) => ({
 *     getPosts: build.query<PostsApiResponse, QueryArgument>({
 *       query: (limit = 5) => `?limit=${limit}&select=title`,
 *     }),
 *   }),
 * })
 *
 * const { useGetPostsQuery } = postsApiSlice
 *
 * function PostById({ id }: { id: number }) {
 *   const { post } = useGetPostsQuery(undefined, {
 *     selectFromResult: (state) => ({
 *       post: state.data?.posts.find((post) => post.id === id),
 *     }),
 *   })
 *
 *   return <li>{post?.title}</li>
 * }
 *
 * const EMPTY_ARRAY: Post[] = []
 *
 * const typedSelectFromResult: TypedQueryStateSelector<
 *   PostsApiResponse,
 *   QueryArgument,
 *   BaseQueryFunction,
 *   SelectedResult
 * > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY })
 *
 * function PostsList() {
 *   const { posts } = useGetPostsQuery(undefined, {
 *     selectFromResult: typedSelectFromResult,
 *   })
 *
 *   return (
 *     <div>
 *       <ul>
 *         {posts.map((post) => (
 *           <PostById key={post.id} id={post.id} />
 *         ))}
 *       </ul>
 *     </div>
 *   )
 * }
 * ```
 *
 * @template ResultType - The type of the result `data` returned by the query.
 * @template QueryArgumentType - The type of the argument passed into the query.
 * @template BaseQueryFunctionType - The type of the base query function being used.
 * @template SelectedResultType - The type of the selected result returned by the __`selectFromResult`__ function.
 *
 * @since 2.3.0
 * @public
 */
export type TypedQueryStateSelector<
  ResultType,
  QueryArgumentType,
  BaseQueryFunctionType extends BaseQueryFn,
  SelectedResultType extends Record<string, any> = UseQueryStateDefaultResult<
    QueryDefinition<
      QueryArgumentType,
      BaseQueryFunctionType,
      string,
      ResultType,
      string
    >
  >,
> = QueryStateSelector<
  SelectedResultType,
  QueryDefinition<
    QueryArgumentType,
    BaseQueryFunctionType,
    string,
    ResultType,
    string
  >
>

/**
 * 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 type UseQueryState<D extends QueryDefinition<any, any, any, any>> = <
  R extends Record<string, any> = UseQueryStateDefaultResult<D>,
>(
  arg: QueryArgFrom<D> | SkipToken,
  options?: UseQueryStateOptions<D, R>,
) => UseQueryStateResult<D, R>

export type TypedUseQueryState<
  ResultType,
  QueryArg,
  BaseQuery extends BaseQueryFn,
> = UseQueryState<
  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
>

/**
 * @internal
 */
export 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>
}

/**
 * Provides a way to define a "pre-typed" version of
 * {@linkcode UseQueryStateOptions} with specific options for a given query.
 * This is particularly useful for setting default query behaviors such as
 * refetching strategies, which can be overridden as needed.
 *
 * @example
 * <caption>#### __Create a `useQuery` hook with default options__</caption>
 *
 * ```ts
 * import type {
 *   SubscriptionOptions,
 *   TypedUseQueryStateOptions,
 * } from '@reduxjs/toolkit/query/react'
 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
 *
 * type Post = {
 *   id: number
 *   name: string
 * }
 *
 * const api = createApi({
 *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
 *   tagTypes: ['Post'],
 *   endpoints: (build) => ({
 *     getPosts: build.query<Post[], void>({
 *       query: () => 'posts',
 *     }),
 *   }),
 * })
 *
 * const { useGetPostsQuery } = api
 *
 * export const useGetPostsQueryWithDefaults = <
 *   SelectedResult extends Record<string, any>,
 * >(
 *   overrideOptions: TypedUseQueryStateOptions<
 *     Post[],
 *     void,
 *     ReturnType<typeof fetchBaseQuery>,
 *     SelectedResult
 *   > &
 *     SubscriptionOptions,
 * ) =>
 *   useGetPostsQuery(undefined, {
 *     // Insert default options here
 *
 *     refetchOnMountOrArgChange: true,
 *     refetchOnFocus: true,
 *     ...overrideOptions,
 *   })
 * ```
 *
 * @template ResultType - The type of the result `data` returned by the query.
 * @template QueryArg - The type of the argument passed into the query.
 * @template BaseQuery - The type of the base query function being used.
 * @template SelectedResult - The type of the selected result returned by the __`selectFromResult`__ function.
 *
 * @since 2.2.8
 * @public
 */
export type TypedUseQueryStateOptions<
  ResultType,
  QueryArg,
  BaseQuery extends BaseQueryFn,
  SelectedResult extends Record<string, any> = UseQueryStateDefaultResult<
    QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
  >,
> = UseQueryStateOptions<
  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>,
  SelectedResult
>

export type UseQueryStateResult<
  _ extends QueryDefinition<any, any, any, any>,
  R,
> = TSHelpersNoInfer<R>

/**
 * Helper type to manually type the result
 * of the `useQueryState` hook in userland code.
 */
export type TypedUseQueryStateResult<
  ResultType,
  QueryArg,
  BaseQuery extends BaseQueryFn,
  R = UseQueryStateDefaultResult<
    QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
  >,
> = TSHelpersNoInfer<R>

type UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> =
  QuerySubState<D> & {
    /**
     * Where `data` tries to hold data as much as possible, also re-using
     * data from the last arguments passed into the hook, this property
     * will always contain the received data from the query, for the current query arguments.
     */
    currentData?: ResultTypeFrom<D>
    /**
     * Query has not started yet.
     */
    isUninitialized: false
    /**
     * Query is currently loading for the first time. No data yet.
     */
    isLoading: false
    /**
     * Query is currently fetching, but might have data from an earlier request.
     */
    isFetching: false
    /**
     * Query has data from a successful load.
     */
    isSuccess: false
    /**
     * Query is currently in "error" state.
     */
    isError: false
  }

type UseQueryStateUninitialized<D extends QueryDefinition<any, any, any, any>> =
  TSHelpersOverride<
    Extract<UseQueryStateBaseResult<D>, { status: QueryStatus.uninitialized }>,
    { isUninitialized: true }
  >

type UseQueryStateLoading<D extends QueryDefinition<any, any, any, any>> =
  TSHelpersOverride<
    UseQueryStateBaseResult<D>,
    { isLoading: true; isFetching: boolean; data: undefined }
  >

type UseQueryStateSuccessFetching<
  D extends QueryDefinition<any, any, any, any>,
> = TSHelpersOverride<
  UseQueryStateBaseResult<D>,
  {
    isSuccess: true
    isFetching: true
    error: undefined
  } & {
    data: ResultTypeFrom<D>
  } & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>
>

type UseQueryStateSuccessNotFetching<
  D extends QueryDefinition<any, any, any, any>,
> = TSHelpersOverride<
  UseQueryStateBaseResult<D>,
  {
    isSuccess: true
    isFetching: false
    error: undefined
  } & {
    data: ResultTypeFrom<D>
    currentData: ResultTypeFrom<D>
  } & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>
>

type UseQueryStateError<D extends QueryDefinition<any, any, any, any>> =
  TSHelpersOverride<
    UseQueryStateBaseResult<D>,
    { isError: true } & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>
  >

type UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> =
  TSHelpersId<
    | UseQueryStateUninitialized<D>
    | UseQueryStateLoading<D>
    | UseQueryStateSuccessFetching<D>
    | UseQueryStateSuccessNotFetching<D>
    | UseQueryStateError<D>
  > & {
    /**
     * @deprecated Included for completeness, but discouraged.
     * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
     * and `isUninitialized` flags instead
     */
    status: QueryStatus
  }

export type LazyInfiniteQueryTrigger<
  D extends InfiniteQueryDefinition<any, any, any, any, any>,
> = {
  /**
   * Triggers a lazy query.
   *
   * By default, this will start a new request even if there is already a value in the cache.
   * If you want to use the cache value and only start a request if there is no cache value, set the second argument to `true`.
   *
   * @remarks
   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().
   *
   * @example
   * ```ts
   * // codeblock-meta title="Using .unwrap with async await"
   * try {
   *   const payload = await getUserById(1).unwrap();
   *   console.log('fulfilled', payload)
   * } catch (error) {
   *   console.error('rejected', error);
   * }
   * ```
   */
  (
    arg: QueryArgFrom<D>,
    direction: InfiniteQueryDirection,
  ): InfiniteQueryActionCreatorResult<D>
}

export type TypedLazyInfiniteQueryTrigger<
  ResultType,
  QueryArg,
  PageParam,
  BaseQuery extends BaseQueryFn,
> = LazyInfiniteQueryTrigger<
  InfiniteQueryDefinition<
    QueryArg,
    PageParam,
    BaseQuery,
    string,
    ResultType,
    string
  >
>

export type UseInfiniteQuerySubscriptionOptions<
  D extends InfiniteQueryDefinition<any, any, any, any, any>,
> = SubscriptionOptions & {
  /**
   * Prevents a query from automatically running.
   *
   * @remarks
   * When `skip` is true (or `skipToken` is passed in as `arg`):
   *
   * - **If the query has cached data:**
   *   * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
   *   * The query will have a status of `uninitialized`
   *   * If `skip: false` is set after the initial load, the cached result will be used
   * - **If the query does not have cached data:**
   *   * The query will have a status of `uninitialized`
   *   * The query will not exist in the state when viewed with the dev tools
   *   * The query will not automatically fetch on mount
   *   * The query will not automatically run when additional components with the same query are added that do run
   *
   * @example
   * ```tsx
   * // codeblock-meta no-transpile title="Skip example"
   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
   *   const { data, error, status } = useGetPokemonByNameQuery(name, {
   *     skip,
   *   });
   *
   *   return (
   *     <div>
   *       {name} - {status}
   *     </div>
   *   );
   * };
   * ```
   */
  skip?: boolean
  /**
   * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.
   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.
   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.
   *
   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
   */
  refetchOnMountOrArgChange?: boolean | number
  initialPageParam?: PageParamFrom<D>
  /**
   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched
   * (due to tag invalidation, polling, arg change configuration, or manual refetching),
   * RTK Query will try to sequentially refetch all pages currently in the cache.
   * When `false` only the first page will be refetched.
   *
   * This option applies to all automatic refetches for this subscription (polling, tag invalidation, etc.).
   * It can be overridden on a per-call basis using the `refetch()` method.
   */
  refetchCachedPages?: boolean
}

export type TypedUseInfiniteQuerySubscription<
  ResultType,
  QueryArg,
  PageParam,
  BaseQuery extends BaseQueryFn,
> = UseInfiniteQuerySubscription<
  InfiniteQueryDefinition<
    QueryArg,
    PageParam,
    BaseQuery,
    string,
    ResultType,
    string
  >
>

export type UseInfiniteQuerySubscriptionResult<
  D extends InfiniteQueryDefinition<any, any, any, any, any>,
> = {
  refetch: (
    options?: Pick<
      UseInfiniteQuerySubscriptionOptions<D>,
      'refetchCachedPages'
    >,
  ) => InfiniteQueryActionCreatorResult<D>
  trigger: LazyInfiniteQueryTrigger<D>
  fetchNextPage: () => InfiniteQueryActionCreatorResult<D>
  fetchPreviousPage: () => InfiniteQueryActionCreatorResult<D>
}

/**
 * Helper type to manually type the result
 * of the `useQuerySubscription` hook in userland code.
 */
export type TypedUseInfiniteQuerySubscriptionResult<
  ResultType,
  QueryArg,
  PageParam,
  BaseQuery extends BaseQueryFn,
> = UseInfiniteQuerySubscriptionResult<
  InfiniteQueryDefinition<
    QueryArg,
    PageParam,
    BaseQuery,
    string,
    ResultType,
    string
  >
>

export type InfiniteQueryStateSelector<
  R extends Record<string, any>,
  D extends InfiniteQueryDefinition<any, any, any, any, any>,
> = (state: UseInfiniteQueryStateDefaultResult<D>) => R

export type TypedInfiniteQueryStateSelector<
  ResultType,
  QueryArg,
  PageParam,
  BaseQuery extends BaseQueryFn,
  SelectedResult extends Record<
    string,
    any
  > = UseInfiniteQueryStateDefaultResult<
    InfiniteQueryDefinition<
      QueryArg,
      PageParam,
      BaseQuery,
      string,
      ResultType,
      string
    >
  >,
> = InfiniteQueryStateSelector<
  SelectedResult,
  InfiniteQueryDefinition<
    QueryArg,
    PageParam,
    BaseQuery,
    string,
    ResultType,
    string
  >
>

/**
 * 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.  Additionally, it will cache multiple "pages" worth of responses within a single cache entry, and allows fetching more pages forwards and backwards from the current cached pages.
 *
 * 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.
 *
 *  The `data` field will be a `{pages: Data[], pageParams: PageParam[]}` structure containing all fetched page responses and the corresponding page param values for each page. You may use this to render individual pages, combine all pages into a single infinite list, or other display logic as needed.
 *
 * This hook combines the functionality of both [`useInfiniteQueryState`](#useinfinitequerystate) and [`useInfiniteQuerySubscription`](#useinfinitequerysubscription) together, and is intended to be used in the majority of situations.
 *
 * As with normal query hooks, `skipToken` is a valid argument that will skip the query from executing.
 *
 * By default, the initial request will use the `initialPageParam` value that was defined on the infinite query endpoint. If you want to start from a different value, you can pass `initialPageParam` as part of the hook options to override that initial request value.
 *
 * Use the returned `fetchNextPage` and `fetchPreviousPage` methods on the hook result object to trigger fetches forwards and backwards. These will always calculate the next or previous page param based on the current cached pages and the provided `getNext/PreviousPageParam` callbacks defined in the endpoint.
 *
 *
 * #### 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
 * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards
 * - 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 type UseInfiniteQuery<
  D extends InfiniteQueryDefinition<any, any, any, any, any>,
> = <R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<D>>(
  arg: InfiniteQueryArgFrom<D> | SkipToken,
  options?: UseInfiniteQuerySubscriptionOptions<D> &
    UseInfiniteQueryStateOptions<D, R>,
) => UseInfiniteQueryHookResult<D, R> &
  Pick<
    UseInfiniteQuerySubscriptionResult<D>,
    'fetchNextPage' | 'fetchPreviousPage'
  >

export type TypedUseInfiniteQuery<
  ResultType,
  QueryArg,
  PageParam,
  BaseQuery extends BaseQueryFn,
> = UseInfiniteQuery<
  InfiniteQueryDefinition<
    QueryArg,
    PageParam,
    BaseQuery,
    string,
    ResultType,
    string
  >
>

/**
 * 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 [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQuerySubscription`](#useinfinitequerysubscription).
 *
 * #### 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 type UseInfiniteQueryState<
  D extends InfiniteQueryDefinition<any, any, any, any, any>,
> = <R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<D>>(
  arg: InfiniteQueryArgFrom<D> | SkipToken,
  options?: UseInfiniteQueryStateOptions<D, R>,
) => UseInfiniteQueryStateResult<D, R>

export type TypedUseInfiniteQueryState<
  ResultType,
  QueryArg,
  PageParam,
  BaseQuery extends BaseQueryFn,
> = UseInfiniteQueryState<
  InfiniteQueryDefinition<
    QueryArg,
    PageParam,
    BaseQuery,
    string,
    ResultType,
    string
  >
>

/**
 * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data. Additionally, it will cache multiple "pages" worth of responses within a single cache entry, and allows fetching more pages forwards and backwards from the current cached pages.
 *
 * 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 [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQueryState`](#useinfinitequerystate).
 *
 * #### 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
 * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards
 * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
 */
export type UseInfiniteQuerySubscription<
  D extends InfiniteQueryDefinition<any, any, any, any, any>,
> = (
  arg: InfiniteQueryArgFrom<D> | SkipToken,
  options?: UseInfiniteQuerySubscriptionOptions<D>,
) => UseInfiniteQuerySubscriptionResult<D>

export type UseInfiniteQueryHookResult<
  D extends InfiniteQueryDefinition<any, any, any, any, any>,
  R = UseInfiniteQueryStateDefaultResult<D>,
> = UseInfiniteQueryStateResult<D, R> &
  Pick<
    UseInfiniteQuerySubscriptionResult<D>,
    'refetch' | 'fetchNextPage' | 'fetchPreviousPage'
  >

export type TypedUseInfiniteQueryHookResult<
  ResultType,
  QueryArg,
  PageParam,
  BaseQuery extends BaseQueryFn,
  R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<
    InfiniteQueryDefinition<
      QueryArg,
      PageParam,
      BaseQuery,
      string,
      ResultType,
      string
    >
  >,
> = UseInfiniteQueryHookResult<
  InfiniteQueryDefinition<
    QueryArg,
    PageParam,
    BaseQuery,
    string,
    ResultType,
    string
  >,
  R
>

export type UseInfiniteQueryStateOptions<
  D extends InfiniteQueryDefinition<any, 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.
   * Note that this should always return an object (not a primitive), as RTKQ adds fields to the return value.
   *
   * @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?: InfiniteQueryStateSelector<R, D>
}

export type TypedUseInfiniteQueryStateOptions<
  ResultType,
  QueryArg,
  PageParam,
  BaseQuery extends BaseQueryFn,
  SelectedResult extends Record<
    string,
    any
  > = UseInfiniteQueryStateDefaultResult<
    InfiniteQueryDefinition<
      QueryArg,
      PageParam,
      BaseQuery,
      string,
      ResultType,
      string
    >
  >,
> = UseInfiniteQueryStateOptions<
  InfiniteQueryDefinition<
    QueryArg,
    PageParam,
    BaseQuery,
    string,
    ResultType,
    string
  >,
  SelectedResult
>

export type UseInfiniteQueryStateResult<
  D extends InfiniteQueryDefinition<any, any, any, any, any>,
  R = UseInfiniteQueryStateDefaultResult<D>,
> = TSHelpersNoInfer<R>

export type TypedUseInfiniteQueryStateResult<
  ResultType,
  QueryArg,
  PageParam,
  BaseQuery extends BaseQueryFn,
  R = UseInfiniteQueryStateDefaultResult<
    InfiniteQueryDefinition<
      QueryArg,
      PageParam,
      BaseQuery,
      string,
      ResultType,
      string
    >
  >,
> = UseInfiniteQueryStateResult<
  InfiniteQueryDefinition<
    QueryArg,
    PageParam,
    BaseQuery,
    string,
    ResultType,
    string
  >,
  R
>

type UseInfiniteQueryStateBaseResult<
  D extends InfiniteQueryDefinition<any, any, any, any, any>,
> = InfiniteQuerySubState<D> & {
  /**
   * Where `data` tries to hold data as much as possible, also re-using
   * data from the last arguments passed into the hook, this property
   * will always contain the received data from the query, for the current query arguments.
   */
  currentData?: InfiniteData<ResultTypeFrom<D>, PageParamFrom<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
  hasNextPage: boolean
  hasPreviousPage: boolean
  isFetchingNextPage: boolean
  isFetchingPreviousPage: boolean
}

type UseInfiniteQueryStateDefaultResult<
  D extends InfiniteQueryDefinition<any, any, any, any, any>,
> = TSHelpersId<
  | TSHelpersOverride<
      Extract<
        UseInfiniteQueryStateBaseResult<D>,
        { status: QueryStatus.uninitialized }
      >,
      { isUninitialized: true }
    >
  | TSHelpersOverride<
      UseInfiniteQueryStateBaseResult<D>,
      | { isLoading: true; isFetching: boolean; data: undefined }
      | ({
          isSuccess: true
          isFetching: true
          error: undefined
        } & Required<
          Pick<
            UseInfiniteQueryStateBaseResult<D>,
            'data' | 'fulfilledTimeStamp'
          >
        >)
      | ({
          isSuccess: true
          isFetching: false
          error: undefined
        } & Required<
          Pick<
            UseInfiniteQueryStateBaseResult<D>,
            'data' | 'fulfilledTimeStamp' | 'currentData'
          >
        >)
      | ({ isError: true } & Required<
          Pick<UseInfiniteQueryStateBaseResult<D>, 'error'>
        >)
    >
> & {
  /**
   * @deprecated Included for completeness, but discouraged.
   * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
   * and `isUninitialized` flags instead
   */
  status: QueryStatus
}

export type MutationStateSelector<
  R extends Record<string, any>,
  D extends MutationDefinition<any, any, any, any>,
> = (state: MutationResultSelectorResult<D>) => R

export type UseMutationStateOptions<
  D extends MutationDefinition<any, any, any, any>,
  R extends Record<string, any>,
> = {
  selectFromResult?: MutationStateSelector<R, D>
  fixedCacheKey?: string
}

export type UseMutationStateResult<
  D extends MutationDefinition<any, any, any, any>,
  R,
> = TSHelpersNoInfer<R> & {
  originalArgs?: QueryArgFrom<D>
  /**
   * Resets the hook state to its initial `uninitialized` state.
   * This will also remove the last result from the cache.
   */
  reset: () => void
}

/**
 * Helper type to manually type the result
 * of the `useMutation` hook in userland code.
 */
export type TypedUseMutationResult<
  ResultType,
  QueryArg,
  BaseQuery extends BaseQueryFn,
  R = MutationResultSelectorResult<
    MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>
  >,
> = UseMutationStateResult<
  MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>,
  R
>

/**
 * A React hook that lets you trigger an update request for a given endpoint, and subscribes the component to read the request status from the Redux store. The component will re-render as the loading status changes.
 *
 * #### Features
 *
 * - Manual control over firing a request to alter data on the server or possibly invalidate the cache
 * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
 * - Returns the latest request status and cached data from the Redux store
 * - Re-renders as the request status changes and data becomes available
 */
export type UseMutation<D extends MutationDefinition<any, any, any, any>> = <
  R extends Record<string, any> = MutationResultSelectorResult<D>,
>(
  options?: UseMutationStateOptions<D, R>,
) => readonly [MutationTrigger<D>, UseMutationStateResult<D, R>]

export type TypedUseMutation<
  ResultType,
  QueryArg,
  BaseQuery extends BaseQueryFn,
> = UseMutation<
  MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>
>

export type MutationTrigger<D extends MutationDefinition<any, any, any, any>> =
  {
    /**
     * Triggers the mutation and returns a Promise.
     * @remarks
     * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
     *
     * @example
     * ```ts
     * // codeblock-meta title="Using .unwrap with async await"
     * try {
     *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();
     *   console.log('fulfilled', payload)
     * } catch (error) {
     *   console.error('rejected', error);
     * }
     * ```
     */
    (arg: QueryArgFrom<D>): MutationActionCreatorResult<D>
  }

export type TypedMutationTrigger<
  ResultType,
  QueryArg,
  BaseQuery extends BaseQueryFn,
> = MutationTrigger<
  MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>
>

/**
 * Wrapper around `defaultQueryStateSelector` to be used in `useQuery`.
 * We want the initial render to already come back with
 * `{ isUninitialized: false, isFetching: true, isLoading: true }`
 * to prevent that the library user has to do an additional check for `isUninitialized`/
 */
const noPendingQueryStateSelector: QueryStateSelector<any, any> = (
  selected,
) => {
  if (selected.isUninitialized) {
    return {
      ...selected,
      isUninitialized: false,
      isFetching: true,
      isLoading: selected.data !== undefined ? false : true,
      // This is the one place where we still have to use `QueryStatus` as an enum,
      // since it's the only reference in the React package and not in the core.
      status: QueryStatus.pending,
    } as any
  }
  return selected
}

function pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {
  const ret: any = {}
  keys.forEach((key) => {
    ret[key] = obj[key]
  })
  return ret
}

const COMMON_HOOK_DEBUG_FIELDS = [
  'data',
  'status',
  'isLoading',
  'isSuccess',
  'isError',
  'error',
] as const

type GenericPrefetchThunk = (
  endpointName: any,
  arg: any,
  options: PrefetchOptions,
) => ThunkAction<void, any, any, UnknownAction>

/**
 *
 * @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 function buildHooks<Definitions extends EndpointDefinitions>({
  api,
  moduleOptions: {
    batch,
    hooks: { useDispatch, useSelector, useStore },
    unstable__sideEffectsInRender,
    createSelector,
  },
  serializeQueryArgs,
  context,
}: {
  api: Api<any, Definitions, any, any, CoreModule>
  moduleOptions: Required<ReactHooksModuleOptions>
  serializeQueryArgs: SerializeQueryArgs<any>
  context: ApiContext<Definitions>
}) {
  const usePossiblyImmediateEffect: (
    effect: () => void | undefined,
    deps?: DependencyList,
  ) => void = unstable__sideEffectsInRender ? (cb) => cb() : useEffect

  type UnsubscribePromiseRef = React.RefObject<
    { unsubscribe?: () => void } | undefined
  >

  const unsubscribePromiseRef = (ref: UnsubscribePromiseRef) =>
    ref.current?.unsubscribe?.()

  const endpointDefinitions = context.endpointDefinitions

  return {
    buildQueryHooks,
    buildInfiniteQueryHooks,
    buildMutationHook,
    usePrefetch,
  }

  function queryStatePreSelector(
    currentState: QueryResultSelectorResult<any>,
    lastResult: UseQueryStateDefaultResult<any> | undefined,
    queryArgs: any,
  ): UseQueryStateDefaultResult<any> {
    // if we had a last result and the current result is uninitialized,
    // we might have called `api.util.resetApiState`
    // in this case, reset the hook
    if (lastResult?.endpointName && currentState.isUninitialized) {
      const { endpointName } = lastResult
      const endpointDefinition = endpointDefinitions[endpointName]
      if (
        queryArgs !== skipToken &&
        serializeQueryArgs({
          queryArgs: lastResult.originalArgs,
          endpointDefinition,
          endpointName,
        }) ===
          serializeQueryArgs({
            queryArgs,
            endpointDefinition,
            endpointName,
          })
      )
        lastResult = undefined
    }

    // data is the last known good request result we have tracked - or if none has been tracked yet the last good result for the current args
    let data = currentState.isSuccess ? currentState.data : lastResult?.data
    if (data === undefined) data = currentState.data

    const hasData = data !== undefined

    // isFetching = true any time a request is in flight
    const isFetching = currentState.isLoading

    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)
    const isLoading =
      (!lastResult || lastResult.isLoading || lastResult.isUninitialized) &&
      !hasData &&
      isFetching

    // isSuccess = true when data is present and we're not refetching after an error.
    // That includes cases where the _current_ item is either actively
    // fetching or about to fetch due to an uninitialized entry.
    const isSuccess =
      currentState.isSuccess ||
      (hasData &&
        ((isFetching && !lastResult?.isError) || currentState.isUninitialized))

    return {
      ...currentState,
      data,
      currentData: currentState.data,
      isFetching,
      isLoading,
      isSuccess,
    } as UseQueryStateDefaultResult<any>
  }

  function infiniteQueryStatePreSelector(
    currentState: InfiniteQueryResultSelectorResult<any>,
    lastResult: UseInfiniteQueryStateDefaultResult<any> | undefined,
    queryArgs: any,
  ): UseInfiniteQueryStateDefaultResult<any> {
    // if we had a last result and the current result is uninitialized,
    // we might have called `api.util.resetApiState`
    // in this case, reset the hook
    if (lastResult?.endpointName && currentState.isUninitialized) {
      const { endpointName } = lastResult
      const endpointDefinition = endpointDefinitions[endpointName]
      if (
        queryArgs !== skipToken &&
        serializeQueryArgs({
          queryArgs: lastResult.originalArgs,
          endpointDefinition,
          endpointName,
        }) ===
          serializeQueryArgs({
            queryArgs,
            endpointDefinition,
            endpointName,
          })
      )
        lastResult = undefined
    }

    // data is the last known good request result we have tracked - or if none has been tracked yet the last good result for the current args
    let data = currentState.isSuccess ? currentState.data : lastResult?.data
    if (data === undefined) data = currentState.data

    const hasData = data !== undefined

    // isFetching = true any time a request is in flight
    const isFetching = currentState.isLoading
    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)
    const isLoading =
      (!lastResult || lastResult.isLoading || lastResult.isUninitialized) &&
      !hasData &&
      isFetching
    // isSuccess = true when data is present
    const isSuccess = currentState.isSuccess || (isFetching && hasData)

    return {
      ...currentState,
      data,
      currentData: currentState.data,
      isFetching,
      isLoading,
      isSuccess,
    } as UseInfiniteQueryStateDefaultResult<any>
  }

  function usePrefetch<EndpointName extends QueryKeys<Definitions>>(
    endpointName: EndpointName,
    defaultOptions?: PrefetchOptions,
  ) {
    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>()
    const stableDefaultOptions = useShallowStableValue(defaultOptions)

    return useCallback(
      (arg: any, options?: PrefetchOptions) =>
        dispatch(
          (api.util.prefetch as GenericPrefetchThunk)(endpointName, arg, {
            ...stableDefaultOptions,
            ...options,
          }),
        ),
      [endpointName, dispatch, stableDefaultOptions],
    )
  }

  function useQuerySubscriptionCommonImpl<
    T extends
      | QueryActionCreatorResult<any>
      | InfiniteQueryActionCreatorResult<any>,
  >(
    endpointName: string,
    arg: unknown | SkipToken,
    {
      refetchOnReconnect,
      refetchOnFocus,
      refetchOnMountOrArgChange,
      skip = false,
      pollingInterval = 0,
      skipPollingIfUnfocused = false,
      ...rest
    }: UseQuerySubscriptionOptions = {},
  ) {
    const { initiate } = api.endpoints[endpointName] as ApiEndpointQuery<
      QueryDefinition<any, any, any, any, any>,
      Definitions
    >
    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>()

    // TODO: Change this to `useRef<SubscriptionSelectors>(undefined)` after upgrading to React 19.
    const subscriptionSelectorsRef = useRef<SubscriptionSelectors | undefined>(
      undefined,
    )

    if (!subscriptionSelectorsRef.current) {
      const returnedValue = dispatch(
        api.internalActions.internal_getRTKQSubscriptions(),
      )

      if (process.env.NODE_ENV !== 'production') {
        if (
          typeof returnedValue !== 'object' ||
          typeof returnedValue?.type === 'string'
        ) {
          throw new Error(
            `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
    You must add the middleware for RTK-Query to function correctly!`,
          )
        }
      }

      subscriptionSelectorsRef.current =
        returnedValue as unknown as SubscriptionSelectors
    }
    const stableArg = useStableQueryArgs(skip ? skipToken : arg)
    const stableSubscriptionOptions = useShallowStableValue({
      refetchOnReconnect,
      refetchOnFocus,
      pollingInterval,
      skipPollingIfUnfocused,
    })

    const initialPageParam = (rest as UseInfiniteQuerySubscriptionOptions<any>)
      .initialPageParam
    const stableInitialPageParam = useShallowStableValue(initialPageParam)

    const refetchCachedPages = (
      rest as UseInfiniteQuerySubscriptionOptions<any>
    ).refetchCachedPages
    const stableRefetchCachedPages = useShallowStableValue(refetchCachedPages)

    /**
     * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.
     */
    const promiseRef = useRef<T | undefined>(undefined)

    let { queryCacheKey, requestId } = promiseRef.current || {}

    // HACK We've saved the middleware subscription lookup callbacks into a ref,
    // so we can directly check here if the subscription exists for this query.
    let currentRenderHasSubscription = false
    if (queryCacheKey && requestId) {
      currentRenderHasSubscription =
        subscriptionSelectorsRef.current.isRequestSubscribed(
          queryCacheKey,
          requestId,
        )
    }

    const subscriptionRemoved =
      !currentRenderHasSubscription && promiseRef.current !== undefined

    usePossiblyImmediateEffect((): void | undefined => {
      if (subscriptionRemoved) {
        promiseRef.current = undefined
      }
    }, [subscriptionRemoved])

    usePossiblyImmediateEffect((): void | undefined => {
      const lastPromise = promiseRef.current
      if (
        typeof process !== 'undefined' &&
        process.env.NODE_ENV === 'removeMeOnCompilation'
      ) {
        // this is only present to enforce the rule of hooks to keep `isSubscribed` in the dependency array
        console.log(subscriptionRemoved)
      }

      if (stableArg === skipToken) {
        lastPromise?.unsubscribe()
        promiseRef.current = undefined
        return
      }

      const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions

      if (!lastPromise || lastPromise.arg !== stableArg) {
        lastPromise?.unsubscribe()
        const promise = dispatch(
          initiate(stableArg, {
            subscriptionOptions: stableSubscriptionOptions,
            forceRefetch: refetchOnMountOrArgChange,
            ...(isInfiniteQueryDefinition(endpointDefinitions[endpointName])
              ? {
                  initialPageParam: stableInitialPageParam,
                  refetchCachedPages: stableRefetchCachedPages,
                }
              : {}),
          }),
        )

        promiseRef.current = promise as T
      } else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
        lastPromise.updateSubscriptionOptions(stableSubscriptionOptions)
      }
    }, [
      dispatch,
      initiate,
      refetchOnMountOrArgChange,
      stableArg,
      stableSubscriptionOptions,
      subscriptionRemoved,
      stableInitialPageParam,
      stableRefetchCachedPages,
      endpointName,
    ])

    return [promiseRef, dispatch, initiate, stableSubscriptionOptions] as const
  }

  function buildUseQueryState(
    endpointName: string,
    preSelector:
      | typeof queryStatePreSelector
      | typeof infiniteQueryStatePreSelector,
  ) {
    const useQueryState = (
      arg: any,
      {
        skip = false,
        selectFromResult,
      }:
        | UseQueryStateOptions<any, any>
        | UseInfiniteQueryStateOptions<any, any> = {},
    ) => {
      const { select } = api.endpoints[endpointName] as ApiEndpointQuery<
        QueryDefinition<any, any, any, any, any>,
        Definitions
      >
      const stableArg = useStableQueryArgs(skip ? skipToken : arg)

      type ApiRootState = Parameters<ReturnType<typeof select>>[0]

      const lastValue = useRef<any>(undefined)

      const selectDefaultResult: Selector<ApiRootState, any, [any]> = useMemo(
        () =>
          // Normally ts-ignores are bad and should be avoided, but we're
          // already casting this selector to be `Selector<any>` anyway,
          // so the inconsistencies don't matter here
          // @ts-ignore
          createSelector(
            [
              // @ts-ignore
              select(stableArg),
              (_: ApiRootState, lastResult: any) => lastResult,
              (_: ApiRootState) => stableArg,
            ],
            preSelector,
            {
              memoizeOptions: {
                resultEqualityCheck: shallowEqual,
              },
            },
          ),
        [select, stableArg],
      )

      const querySelector: Selector<ApiRootState, any, [any]> = useMemo(
        () =>
          selectFromResult
            ? createSelector([selectDefaultResult], selectFromResult, {
                devModeChecks: { identityFunctionCheck: 'never' },
              })
            : selectDefaultResult,
        [selectDefaultResult, selectFromResult],
      )

      const currentState = useSelector(
        (state: RootState<Definitions, any, any>) =>
          querySelector(state, lastValue.current),
        shallowEqual,
      )

      const store = useStore<RootState<Definitions, any, any>>()
      const newLastValue = selectDefaultResult(
        store.getState(),
        lastValue.current,
      )
      useIsomorphicLayoutEffect(() => {
        lastValue.current = newLastValue
      }, [newLastValue])

      return currentState
    }

    return useQueryState
  }

  function usePromiseRefUnsubscribeOnUnmount(
    promiseRef: UnsubscribePromiseRef,
  ) {
    useEffect(() => {
      return () => {
        unsubscribePromiseRef(promiseRef)
        // eslint-disable-next-line react-hooks/exhaustive-deps
        ;(promiseRef.current as any) = undefined
      }
    }, [promiseRef])
  }

  function refetchOrErrorIfUnmounted<
    T extends
      | QueryActionCreatorResult<any>
      | InfiniteQueryActionCreatorResult<any>,
  >(promiseRef: React.RefObject<T | undefined>): T {
    if (!promiseRef.current)
      throw new Error('Cannot refetch a query that has not been started yet.')
    return promiseRef.current.refetch() as T
  }

  function buildQueryHooks(endpointName: string): QueryHooks<any> {
    const useQuerySubscription: UseQuerySubscription<any> = (
      arg: any,
      options = {},
    ) => {
      const [promiseRef] = useQuerySubscriptionCommonImpl<
        QueryActionCreatorResult<any>
      >(endpointName, arg, options)

      usePromiseRefUnsubscribeOnUnmount(promiseRef)

      return useMemo(
        () => ({
          /**
           * A method to manually refetch data for the query
           */
          refetch: () => refetchOrErrorIfUnmounted(promiseRef),
        }),
        [promiseRef],
      )
    }

    const useLazyQuerySubscription: UseLazyQuerySubscription<any> = ({
      refetchOnReconnect,
      refetchOnFocus,
      pollingInterval = 0,
      skipPollingIfUnfocused = false,
    } = {}) => {
      const { initiate } = api.endpoints[endpointName] as ApiEndpointQuery<
        QueryDefinition<any, any, any, any, any>,
        Definitions
      >
      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>()

      const [arg, setArg] = useState<any>(UNINITIALIZED_VALUE)

      // TODO: Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.
      /**
       * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.
       */
      const promiseRef = useRef<QueryActionCreatorResult<any> | undefined>(
        undefined,
      )

      const stableSubscriptionOptions = useShallowStableValue({
        refetchOnReconnect,
        refetchOnFocus,
        pollingInterval,
        skipPollingIfUnfocused,
      })

      usePossiblyImmediateEffect(() => {
        const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions

        if (stableSubscriptionOptions !== lastSubscriptionOptions) {
          promiseRef.current?.updateSubscriptionOptions(
            stableSubscriptionOptions,
          )
        }
      }, [stableSubscriptionOptions])

      const subscriptionOptionsRef = useRef(stableSubscriptionOptions)
      usePossiblyImmediateEffect(() => {
        subscriptionOptionsRef.current = stableSubscriptionOptions
      }, [stableSubscriptionOptions])

      const trigger = useCallback(
        function (arg: any, preferCacheValue = false) {
          let promise: QueryActionCreatorResult<any>

          batch(() => {
            unsubscribePromiseRef(promiseRef)

            promiseRef.current = promise = dispatch(
              initiate(arg, {
                subscriptionOptions: subscriptionOptionsRef.current,
                forceRefetch: !preferCacheValue,
              }),
            )

            setArg(arg)
          })

          return promise!
        },
        [dispatch, initiate],
      )

      const reset = useCallback(() => {
        if (promiseRef.current?.queryCacheKey) {
          dispatch(
            api.internalActions.removeQueryResult({
              queryCacheKey: promiseRef.current?.queryCacheKey as QueryCacheKey,
            }),
          )
        }
      }, [dispatch])

      /* cleanup on unmount */
      useEffect(() => {
        return () => {
          unsubscribePromiseRef(promiseRef)
        }
      }, [])

      /* if "cleanup on unmount" was triggered from a fast refresh, we want to reinstate the query */
      useEffect(() => {
        if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
          trigger(arg, true)
        }
      }, [arg, trigger])

      return useMemo(
        () => [trigger, arg, { reset }] as const,
        [trigger, arg, reset],
      )
    }

    const useQueryState: UseQueryState<any> = buildUseQueryState(
      endpointName,
      queryStatePreSelector,
    )

    return {
      useQueryState,
      useQuerySubscription,
      useLazyQuerySubscription,
      useLazyQuery(options) {
        const [trigger, arg, { reset }] = useLazyQuerySubscription(options)
        const queryStateResults = useQueryState(arg, {
          ...options,
          skip: arg === UNINITIALIZED_VALUE,
        })

        const info = useMemo(() => ({ lastArg: arg }), [arg])
        return useMemo(
          () => [trigger, { ...queryStateResults, reset }, info],
          [trigger, queryStateResults, reset, info],
        )
      },
      useQuery(arg, options) {
        const querySubscriptionResults = useQuerySubscription(arg, options)
        const queryStateResults = useQueryState(arg, {
          selectFromResult:
            arg === skipToken || options?.skip
              ? undefined
              : noPendingQueryStateSelector,
          ...options,
        })

        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS)
        useDebugValue(debugValue)

        return useMemo(
          () => ({ ...queryStateResults, ...querySubscriptionResults }),
          [queryStateResults, querySubscriptionResults],
        )
      },
    }
  }

  function buildInfiniteQueryHooks(
    endpointName: string,
  ): InfiniteQueryHooks<any> {
    const useInfiniteQuerySubscription: UseInfiniteQuerySubscription<any> = (
      arg: any,
      options = {},
    ) => {
      const [promiseRef, dispatch, initiate, stableSubscriptionOptions] =
        useQuerySubscriptionCommonImpl<InfiniteQueryActionCreatorResult<any>>(
          endpointName,
          arg,
          options,
        )

      const subscriptionOptionsRef = useRef(stableSubscriptionOptions)
      usePossiblyImmediateEffect(() => {
        subscriptionOptionsRef.current = stableSubscriptionOptions
      }, [stableSubscriptionOptions])

      // Extract and stabilize the hook-level refetchCachedPages option
      const hookRefetchCachedPages = (
        options as UseInfiniteQuerySubscriptionOptions<any>
      ).refetchCachedPages
      const stableHookRefetchCachedPages = useShallowStableValue(
        hookRefetchCachedPages,
      )

      const trigger: LazyInfiniteQueryTrigger<any> = useCallback(
        function (arg: unknown, direction: 'forward' | 'backward') {
          let promise: InfiniteQueryActionCreatorResult<any>

          batch(() => {
            unsubscribePromiseRef(promiseRef)

            promiseRef.current = promise = dispatch(
              (initiate as StartInfiniteQueryActionCreator<any>)(arg, {
                subscriptionOptions: subscriptionOptionsRef.current,
                direction,
              }),
            )
          })

          return promise!
        },
        [promiseRef, dispatch, initiate],
      )

      usePromiseRefUnsubscribeOnUnmount(promiseRef)

      const stableArg = useStableQueryArgs(options.skip ? skipToken : arg)

      const refetch = useCallback(
        (
          options?: Pick<
            UseInfiniteQuerySubscriptionOptions<any>,
            'refetchCachedPages'
          >,
        ) => {
          if (!promiseRef.current)
            throw new Error(
              'Cannot refetch a query that has not been started yet.',
            )
          // Merge per-call options with hook-level default
          const mergedOptions = {
            refetchCachedPages:
              options?.refetchCachedPages ?? stableHookRefetchCachedPages,
          }
          return promiseRef.current.refetch(mergedOptions)
        },
        [promiseRef, stableHookRefetchCachedPages],
      )

      return useMemo(() => {
        const fetchNextPage = () => {
          return trigger(stableArg, 'forward')
        }

        const fetchPreviousPage = () => {
          return trigger(stableArg, 'backward')
        }

        return {
          trigger,
          /**
           * A method to manually refetch data for the query
           */
          refetch,
          fetchNextPage,
          fetchPreviousPage,
        }
      }, [refetch, trigger, stableArg])
    }

    const useInfiniteQueryState: UseInfiniteQueryState<any> =
      buildUseQueryState(endpointName, infiniteQueryStatePreSelector)

    return {
      useInfiniteQueryState,
      useInfiniteQuerySubscription,
      useInfiniteQuery(arg, options) {
        const { refetch, fetchNextPage, fetchPreviousPage } =
          useInfiniteQuerySubscription(arg, options)
        const queryStateResults = useInfiniteQueryState(arg, {
          selectFromResult:
            arg === skipToken || options?.skip
              ? undefined
              : noPendingQueryStateSelector,
          ...options,
        })

        const debugValue = pick(
          queryStateResults,
          ...COMMON_HOOK_DEBUG_FIELDS,
          'hasNextPage',
          'hasPreviousPage',
        )
        useDebugValue(debugValue)

        return useMemo(
          () => ({
            ...queryStateResults,
            fetchNextPage,
            fetchPreviousPage,
            refetch,
          }),
          [queryStateResults, fetchNextPage, fetchPreviousPage, refetch],
        )
      },
    }
  }

  function buildMutationHook(name: string): UseMutation<any> {
    return ({ selectFromResult, fixedCacheKey } = {}) => {
      const { select, initiate } = api.endpoints[name] as ApiEndpointMutation<
        MutationDefinition<any, any, any, any, any>,
        Definitions
      >
      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>()
      const [promise, setPromise] = useState<MutationActionCreatorResult<any>>()

      useEffect(
        () => () => {
          if (!promise?.arg.fixedCacheKey) {
            promise?.reset()
          }
        },
        [promise],
      )

      const triggerMutation = useCallback(
        function (arg: Parameters<typeof initiate>['0']) {
          const promise = dispatch(initiate(arg, { fixedCacheKey }))
          setPromise(promise)
          return promise
        },
        [dispatch, initiate, fixedCacheKey],
      )

      const { requestId } = promise || {}
      const selectDefaultResult = useMemo(
        () => select({ fixedCacheKey, requestId: promise?.requestId }),
        [fixedCacheKey, promise, select],
      )
      const mutationSelector = useMemo(
        (): Selector<RootState<Definitions, any, any>, any> =>
          selectFromResult
            ? createSelector([selectDefaultResult], selectFromResult)
            : selectDefaultResult,
        [selectFromResult, selectDefaultResult],
      )

      const currentState = useSelector(mutationSelector, shallowEqual)
      const originalArgs =
        fixedCacheKey == null ? promise?.arg.originalArgs : undefined
      const reset = useCallback(() => {
        batch(() => {
          if (promise) {
            setPromise(undefined)
          }
          if (fixedCacheKey) {
            dispatch(
              api.internalActions.removeMutationResult({
                requestId,
                fixedCacheKey,
              }),
            )
          }
        })
      }, [dispatch, fixedCacheKey, promise, requestId])

      const debugValue = pick(
        currentState,
        ...COMMON_HOOK_DEBUG_FIELDS,
        'endpointName',
      )
      useDebugValue(debugValue)

      const finalState = useMemo(
        () => ({ ...currentState, originalArgs, reset }),
        [currentState, originalArgs, reset],
      )

      return useMemo(
        () => [triggerMutation, finalState] as const,
        [triggerMutation, finalState],
      )
    }
  }
}