Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow customising createSelector instance used by RTKQ #4048

Merged
merged 5 commits into from
Jan 15, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions docs/rtk-query/usage/customizing-create-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,27 @@ const customCreateApi = buildCreateApi(
)
```

## Customizing `createSelector` for RTKQ

Both `coreModule` and `reactHooksModule` accept a `createSelector` option which should be a selector creator instance from Reselect or with an equivalent signature.

```ts
import * as React from 'react'
import { createSelectorCreator, lruMemoize } from '@reduxjs/toolkit'
import {
buildCreateApi,
coreModule,
reactHooksModule,
} from '@reduxjs/toolkit/query/react'

const createLruSelector = createSelectorCreator(lruMemoize)

const customCreateApi = buildCreateApi(
coreModule({ createSelector: createLruSelector }),
reactHooksModule({ createSelector: createLruSelector })
)
```

## Creating your own module

If you want to create your own module, you should review [the react-hooks module](https://github.com/reduxjs/redux-toolkit/blob/b74a52935a5840bebca5acdc8e2265e3b6497afa/src/query/react/module.ts) to see what an implementation would look like.
Expand Down
5 changes: 4 additions & 1 deletion packages/toolkit/src/query/core/buildSelectors.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createNextState, createSelector } from './rtkImports'
import type { createSelector as _createSelector } from './rtkImports'
import { createNextState } from './rtkImports'
EskiMojo14 marked this conversation as resolved.
Show resolved Hide resolved
import type {
MutationSubState,
QuerySubState,
Expand Down Expand Up @@ -123,9 +124,11 @@ export function buildSelectors<
>({
serializeQueryArgs,
reducerPath,
createSelector,
}: {
serializeQueryArgs: InternalSerializeQueryArgs
reducerPath: ReducerPath
createSelector: typeof _createSelector
}) {
type RootState = _RootState<Definitions, string, string>

Expand Down
13 changes: 12 additions & 1 deletion packages/toolkit/src/query/core/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import type { ReferenceCacheLifecycle } from './buildMiddleware/cacheLifecycle'
import type { ReferenceQueryLifecycle } from './buildMiddleware/queryLifecycle'
import type { ReferenceCacheCollection } from './buildMiddleware/cacheCollection'
import { enablePatches } from 'immer'
import { createSelector as _createSelector } from './rtkImports'

/**
* `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_
Expand Down Expand Up @@ -431,6 +432,13 @@ export type ListenerActions = {

export type InternalActions = SliceActions & ListenerActions

export interface CoreModuleOptions {
/**
* A selector creator (usually from `reselect`, or matching the same signature)
*/
createSelector?: typeof _createSelector
}

/**
* Creates a module containing the basic redux logic for use with `buildCreateApi`.
*
Expand All @@ -439,7 +447,9 @@ export type InternalActions = SliceActions & ListenerActions
* const createBaseApi = buildCreateApi(coreModule());
* ```
*/
export const coreModule = (): Module<CoreModule> => ({
export const coreModule = ({
createSelector = _createSelector,
}: CoreModuleOptions = {}): Module<CoreModule> => ({
name: coreModuleName,
init(
api,
Expand Down Expand Up @@ -548,6 +558,7 @@ export const coreModule = (): Module<CoreModule> => ({
} = buildSelectors({
serializeQueryArgs: serializeQueryArgs as any,
reducerPath,
createSelector,
})

safeAssign(api.util, { selectInvalidatedBy, selectCachedArgsForQuery })
Expand Down
6 changes: 2 additions & 4 deletions packages/toolkit/src/query/react/buildHooks.ts
EskiMojo14 marked this conversation as resolved.
Show resolved Hide resolved
EskiMojo14 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,7 @@ import { UNINITIALIZED_VALUE } from './constants'
import { useShallowStableValue } from './useShallowStableValue'
import type { BaseQueryFn } from '../baseQueryTypes'
import { defaultSerializeQueryArgs } from '../defaultSerializeQueryArgs'
import {
InternalMiddlewareState,
SubscriptionSelectors,
} from '../core/buildMiddleware/types'
import type { SubscriptionSelectors } from '../core/buildMiddleware/types'

// Copy-pasted from React-Redux
export const useIsomorphicLayoutEffect =
Expand Down Expand Up @@ -582,6 +579,7 @@ export function buildHooks<Definitions extends EndpointDefinitions>({
batch,
hooks: { useDispatch, useSelector, useStore },
unstable__sideEffectsInRender,
createSelector,
},
serializeQueryArgs,
context,
Expand Down
7 changes: 7 additions & 0 deletions packages/toolkit/src/query/react/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
import type { QueryKeys } from '../core/apiState'
import type { PrefetchOptions } from '../core/module'
import { countObjectKeys } from '../utils/countObjectKeys'
import { createSelector as _createSelector } from 'reselect'

export const reactHooksModuleName = /* @__PURE__ */ Symbol()
export type ReactHooksModule = typeof reactHooksModuleName
Expand Down Expand Up @@ -111,6 +112,10 @@ export interface ReactHooksModuleOptions {
* ```
*/
unstable__sideEffectsInRender?: boolean
/**
* A selector creator (usually from `reselect`, or matching the same signature)
*/
createSelector?: typeof _createSelector
}

/**
Expand Down Expand Up @@ -140,6 +145,7 @@ export const reactHooksModule = ({
useSelector: rrUseSelector,
useStore: rrUseStore,
},
createSelector = _createSelector,
unstable__sideEffectsInRender = false,
...rest
}: ReactHooksModuleOptions = {}): Module<ReactHooksModule> => {
Expand Down Expand Up @@ -191,6 +197,7 @@ export const reactHooksModule = ({
batch,
hooks,
unstable__sideEffectsInRender,
createSelector,
},
serializeQueryArgs,
context,
Expand Down
68 changes: 67 additions & 1 deletion packages/toolkit/src/query/tests/buildCreateApi.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,12 @@ import { server } from './mocks/server'
import type { UnknownAction } from 'redux'
import type { SubscriptionOptions } from '@reduxjs/toolkit/dist/query/core/apiState'
import type { SerializedError } from '@reduxjs/toolkit'
import { createListenerMiddleware, configureStore } from '@reduxjs/toolkit'
import {
createListenerMiddleware,
configureStore,
lruMemoize,
createSelectorCreator,
} from '@reduxjs/toolkit'
import { delay } from '../../utils'

const MyContext = React.createContext<ReactReduxContextValue>(null as any)
Expand Down Expand Up @@ -123,4 +128,65 @@ describe('buildCreateApi', () => {
`"When using custom hooks for context, all 3 hooks need to be provided: useDispatch, useSelector, useStore.\nHook useStore was either not provided or not a function."`
)
})
test('allows passing createSelector instance', async () => {
const memoize = vi.fn(lruMemoize)
const createSelector = createSelectorCreator(memoize)
const createApi = buildCreateApi(
coreModule({ createSelector }),
reactHooksModule({ createSelector })
)
const api = createApi({
baseQuery: async (arg: any) => {
await waitMs()

return {
data: arg?.body ? { ...arg.body } : {},
}
},
endpoints: (build) => ({
getUser: build.query<{ name: string }, number>({
query: () => ({
body: { name: 'Timmy' },
}),
}),
}),
})

const storeRef = setupApiStore(api, {}, { withoutTestLifecycles: true })

await storeRef.store.dispatch(api.endpoints.getUser.initiate(1))

const selectUser = api.endpoints.getUser.select(1)

expect(selectUser(storeRef.store.getState()).data).toEqual({
name: 'Timmy',
})

expect(memoize).toHaveBeenCalledTimes(4)

memoize.mockClear()

function User() {
const { isFetching } = api.endpoints.getUser.useQuery(1)

return (
<div>
<div data-testid="isFetching">{String(isFetching)}</div>
</div>
)
}

function Wrapper({ children }: any) {
return <Provider store={storeRef.store}>{children}</Provider>
}

render(<User />, { wrapper: Wrapper })

await waitFor(() =>
expect(screen.getByTestId('isFetching').textContent).toBe('false')
)

// select() + selectFromResult
expect(memoize).toHaveBeenCalledTimes(8)
})
})
Loading