Skip to content

Commit

Permalink
Merge branch 'master' into combineslices-example
Browse files Browse the repository at this point in the history
  • Loading branch information
EskiMojo14 committed Nov 29, 2024
2 parents dd45e4e + e848a55 commit a39d645
Show file tree
Hide file tree
Showing 47 changed files with 1,294 additions and 308 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ jobs:
fail-fast: false
matrix:
node: ['20.x']
ts: ['4.7', '4.8', '4.9', '5.0', '5.1', '5.2', '5.3', '5.4', '5.5']
ts: ['5.0', '5.1', '5.2', '5.3', '5.4', '5.5']
steps:
- name: Checkout repo
uses: actions/checkout@v4
Expand Down
54 changes: 50 additions & 4 deletions docs/rtk-query/api/fetchBaseQuery.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,60 @@ type FetchBaseQueryResult = Promise<
meta?: { request: Request; response: Response }
}
| {
error: {
status: number
data: any
}
error: FetchBaseQueryError
data?: undefined
meta?: { request: Request; response: Response }
}
>

type FetchBaseQueryError =
| {
/**
* * `number`:
* HTTP status code
*/
status: number
data: unknown
}
| {
/**
* * `"FETCH_ERROR"`:
* An error that occurred during execution of `fetch` or the `fetchFn` callback option
**/
status: 'FETCH_ERROR'
data?: undefined
error: string
}
| {
/**
* * `"PARSING_ERROR"`:
* An error happened during parsing.
* Most likely a non-JSON-response was returned with the default `responseHandler` "JSON",
* or an error occurred while executing a custom `responseHandler`.
**/
status: 'PARSING_ERROR'
originalStatus: number
data: string
error: string
}
| {
/**
* * `"TIMEOUT_ERROR"`:
* Request timed out
**/
status: 'TIMEOUT_ERROR'
data?: undefined
error: string
}
| {
/**
* * `"CUSTOM_ERROR"`:
* A custom error type that you can return from your `queryFn` where another error might not make sense.
**/
status: 'CUSTOM_ERROR'
data?: unknown
error: string
}
```
## Parameters
Expand Down
2 changes: 1 addition & 1 deletion docs/rtk-query/usage/customizing-queries.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,7 @@ const staggeredBaseQueryWithBailOut = retry(
// bail out of re-tries immediately if unauthorized,
// because we know successive re-retries would be redundant
if (result.error?.status === 401) {
retry.fail(result.error)
retry.fail(result.error, result.meta)
}

return result
Expand Down
3 changes: 2 additions & 1 deletion examples/query/react/basic/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
"react-scripts": "5.0.1"
},
"devDependencies": {
"@testing-library/react": "^13.3.0",
"@testing-library/dom": "^10.4.0",
"@testing-library/react": "^16.0.1",
"@types/jest": "^26.0.23",
"@types/react": "^18.0.5",
"@types/react-dom": "^18.0.5",
Expand Down
3 changes: 2 additions & 1 deletion examples/query/react/kitchen-sink/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
"react-scripts": "5.0.1"
},
"devDependencies": {
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^5.11.5",
"@testing-library/react": "^13.3.0",
"@testing-library/react": "^16.0.1",
"@types/jest": "^26.0.23",
"@types/node": "^14.14.6",
"@types/react": "^18.0.5",
Expand Down
7 changes: 4 additions & 3 deletions packages/toolkit/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@reduxjs/toolkit",
"version": "2.3.0",
"version": "2.4.0",
"description": "The official, opinionated, batteries-included toolset for efficient Redux development",
"author": "Mark Erikson <[email protected]>",
"license": "MIT",
Expand Down Expand Up @@ -56,8 +56,9 @@
"@phryneas/ts-version": "^1.0.2",
"@size-limit/file": "^11.0.1",
"@size-limit/webpack": "^11.0.1",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.1.5",
"@testing-library/dom": "^10.4.0",
"@testing-library/react": "^16.0.1",
"@testing-library/user-event": "^14.5.2",
"@types/babel__core": "^7.20.5",
"@types/babel__helper-module-imports": "^7.18.3",
"@types/json-stringify-safe": "^5.0.0",
Expand Down
12 changes: 4 additions & 8 deletions packages/toolkit/src/autoBatchEnhancer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,6 @@ const createQueueWithTimer = (timeout: number) => {
}
}

// requestAnimationFrame won't exist in SSR environments.
// Fall back to a vague approximation just to keep from erroring.
const rAF =
typeof window !== 'undefined' && window.requestAnimationFrame
? window.requestAnimationFrame
: createQueueWithTimer(10)

export type AutoBatchOptions =
| { type: 'tick' }
| { type: 'timer'; timeout: number }
Expand Down Expand Up @@ -66,7 +59,10 @@ export const autoBatchEnhancer =
options.type === 'tick'
? queueMicrotask
: options.type === 'raf'
? rAF
? // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.
typeof window !== 'undefined' && window.requestAnimationFrame
? window.requestAnimationFrame
: createQueueWithTimer(10)
: options.type === 'callback'
? options.queueNotification
: createQueueWithTimer(options.timeout)
Expand Down
10 changes: 6 additions & 4 deletions packages/toolkit/src/combineSlices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type {
UnionToIntersection,
WithOptionalProp,
} from './tsHelpers'
import { emplace } from './utils'
import { getOrInsertComputed } from './utils'

type SliceLike<ReducerPath extends string, State> = {
reducerPath: ReducerPath
Expand Down Expand Up @@ -324,8 +324,10 @@ const createStateProxy = <State extends object>(
state: State,
reducerMap: Partial<Record<string, Reducer>>,
) =>
emplace(stateProxyMap, state, {
insert: () =>
getOrInsertComputed(
stateProxyMap,
state,
() =>
new Proxy(state, {
get: (target, prop, receiver) => {
if (prop === ORIGINAL_STATE) return target
Expand All @@ -350,7 +352,7 @@ const createStateProxy = <State extends object>(
return result
},
}),
}) as State
) as State

const original = (state: any) => {
if (!isStateProxy(state)) {
Expand Down
15 changes: 10 additions & 5 deletions packages/toolkit/src/createAsyncThunk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,9 @@ export type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<
NewConfig & Omit<OldConfig, keyof NewConfig>
>

type CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> = {
export type CreateAsyncThunkFunction<
CurriedThunkApiConfig extends AsyncThunkConfig,
> = {
/**
*
* @param typePrefix
Expand Down Expand Up @@ -481,12 +483,15 @@ type CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> = {
ThunkArg,
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
>

withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
>
}

type CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> =
CreateAsyncThunkFunction<CurriedThunkApiConfig> & {
withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
>
}

export const createAsyncThunk = /* @__PURE__ */ (() => {
function createAsyncThunk<
Returned,
Expand Down
40 changes: 20 additions & 20 deletions packages/toolkit/src/createSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { createReducer } from './createReducer'
import type { ActionReducerMapBuilder, TypedActionCreator } from './mapBuilders'
import { executeReducerBuilderCallback } from './mapBuilders'
import type { Id, TypeGuard } from './tsHelpers'
import { emplace } from './utils'
import { getOrInsertComputed } from './utils'

const asyncThunkSymbol = /* @__PURE__ */ Symbol.for(
'rtk-slice-createasyncthunk',
Expand Down Expand Up @@ -769,25 +769,25 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) {
function getSelectors(
selectState: (rootState: any) => State = selectSelf,
) {
const selectorCache = emplace(injectedSelectorCache, injected, {
insert: () => new WeakMap(),
})

return emplace(selectorCache, selectState, {
insert: () => {
const map: Record<string, Selector<any, any>> = {}
for (const [name, selector] of Object.entries(
options.selectors ?? {},
)) {
map[name] = wrapSelector(
selector,
selectState,
getInitialState,
injected,
)
}
return map
},
const selectorCache = getOrInsertComputed(
injectedSelectorCache,
injected,
() => new WeakMap(),
)

return getOrInsertComputed(selectorCache, selectState, () => {
const map: Record<string, Selector<any, any>> = {}
for (const [name, selector] of Object.entries(
options.selectors ?? {},
)) {
map[name] = wrapSelector(
selector,
selectState,
getInitialState,
injected,
)
}
return map
}) as any
}
return {
Expand Down
19 changes: 7 additions & 12 deletions packages/toolkit/src/dynamicMiddleware/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { compose } from 'redux'
import { createAction } from '../createAction'
import { isAllOf } from '../matchers'
import { nanoid } from '../nanoid'
import { emplace, find } from '../utils'
import { getOrInsertComputed } from '../utils'
import type {
AddMiddleware,
DynamicMiddleware,
Expand All @@ -23,7 +23,6 @@ const createMiddlewareEntry = <
>(
middleware: Middleware<any, State, DispatchType>,
): MiddlewareEntry<State, DispatchType> => ({
id: nanoid(),
middleware,
applied: new Map(),
})
Expand All @@ -38,7 +37,10 @@ export const createDynamicMiddleware = <
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
>(): DynamicMiddlewareInstance<State, DispatchType> => {
const instanceId = nanoid()
const middlewareMap = new Map<string, MiddlewareEntry<State, DispatchType>>()
const middlewareMap = new Map<
Middleware<any, State, DispatchType>,
MiddlewareEntry<State, DispatchType>
>()

const withMiddleware = Object.assign(
createAction(
Expand All @@ -58,22 +60,15 @@ export const createDynamicMiddleware = <
...middlewares: Middleware<any, State, DispatchType>[]
) {
middlewares.forEach((middleware) => {
let entry = find(
Array.from(middlewareMap.values()),
(entry) => entry.middleware === middleware,
)
if (!entry) {
entry = createMiddlewareEntry(middleware)
}
middlewareMap.set(entry.id, entry)
getOrInsertComputed(middlewareMap, middleware, createMiddlewareEntry)
})
},
{ withTypes: () => addMiddleware },
) as AddMiddleware<State, DispatchType>

const getFinalMiddleware: Middleware<{}, State, DispatchType> = (api) => {
const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) =>
emplace(entry.applied, api, { insert: () => entry.middleware(api) }),
getOrInsertComputed(entry.applied, api, entry.middleware),
)
return compose(...appliedMiddleware)
}
Expand Down
1 change: 0 additions & 1 deletion packages/toolkit/src/dynamicMiddleware/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ export type MiddlewareEntry<
State = unknown,
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
> = {
id: string
middleware: Middleware<any, State, DispatchType>
applied: Map<
MiddlewareAPI<DispatchType, State>,
Expand Down
1 change: 1 addition & 0 deletions packages/toolkit/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ export type {
GetState,
GetThunkAPI,
SerializedError,
CreateAsyncThunkFunction,
} from './createAsyncThunk'

export {
Expand Down
Loading

0 comments on commit a39d645

Please sign in to comment.