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

wrap selector factories in createSelector.memoize (weakMapMemoize by default) #4164

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 17 additions & 4 deletions packages/toolkit/src/query/core/buildSelectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,11 @@ export function buildSelectors<
const selectSkippedQuery = (state: RootState) => defaultQuerySubState
const selectSkippedMutation = (state: RootState) => defaultMutationSubState

const aMemoizedSelector = createSelector(
() => {},
() => ({}),
)

return {
buildQuerySelector,
buildMutationSelector,
Expand Down Expand Up @@ -169,7 +174,7 @@ export function buildSelectors<
endpointName: string,
endpointDefinition: QueryDefinition<any, any, any, any>,
) {
return ((queryArgs: any) => {
const memoized = aMemoizedSelector.memoize((queryArgs: any) => {
const serializedArgs = serializeQueryArgs({
queryArgs,
endpointDefinition,
Expand All @@ -182,11 +187,15 @@ export function buildSelectors<
queryArgs === skipToken ? selectSkippedQuery : selectQuerySubstate

return createSelector(finalSelectQuerySubState, withRequestFlags)
}) as QueryResultSelectorFactory<any, RootState>
})
return Object.assign(
(arg: any) => memoized(arg),
memoized,
) as QueryResultSelectorFactory<any, RootState>
}

function buildMutationSelector() {
return ((id) => {
const memoized = aMemoizedSelector.memoize((id) => {
let mutationId: string | typeof skipToken
if (typeof id === 'object') {
mutationId = getMutationCacheKey(id) ?? skipToken
Expand All @@ -202,7 +211,11 @@ export function buildSelectors<
: selectMutationSubstate

return createSelector(finalSelectMutationSubstate, withRequestFlags)
}) as MutationResultSelectorFactory<any, RootState>
})
return Object.assign(
(arg: any) => memoized(arg),
memoized,
) as MutationResultSelectorFactory<any, RootState>
}

function selectInvalidatedBy(
Expand Down
2 changes: 1 addition & 1 deletion packages/toolkit/src/query/tests/buildCreateApi.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,6 @@ describe('buildCreateApi', () => {
)

// select() + selectFromResult
expect(memoize).toHaveBeenCalledTimes(8)
expect(memoize).toHaveBeenCalledTimes(4)
})
})
124 changes: 124 additions & 0 deletions packages/toolkit/src/query/tests/buildSelector.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import {
buildCreateApi,
coreModule,
createApi,
fetchBaseQuery,
reactHooksModule,
} from '@reduxjs/toolkit/query/react'
import { setupApiStore } from '../../tests/utils/helpers'
import {
createSelectorCreator,
lruMemoize,
type weakMapMemoize,
} from 'reselect'
import { assertCast } from '../tsHelpers'

describe('buildSelector', () => {
interface Todo {
userId: number
id: number
title: string
completed: boolean
}

type Todos = Array<Todo>

const exampleApi = createApi({
baseQuery: fetchBaseQuery({
baseUrl: 'https://jsonplaceholder.typicode.com',
}),
endpoints: (build) => ({
getTodos: build.query<Todos, void>({
query: () => '/todos',
}),
getTodo: build.query<Todo, string>({
query: (id) => `/todos/${id}`,
}),
}),
})

const store = setupApiStore(exampleApi)
it('should memoize selector creation', () => {
expect(exampleApi.endpoints.getTodo.select('1')).toBe(
exampleApi.endpoints.getTodo.select('1'),
)

expect(exampleApi.endpoints.getTodo.select('1')).not.toBe(
exampleApi.endpoints.getTodo.select('2'),
)

expect(
exampleApi.endpoints.getTodo.select('1')(store.store.getState()),
).toBe(exampleApi.endpoints.getTodo.select('1')(store.store.getState()))

expect(exampleApi.endpoints.getTodos.select()).toBe(
exampleApi.endpoints.getTodos.select(undefined),
)
})
it('exposes memoize methods on select (untyped)', () => {
assertCast<
typeof exampleApi.endpoints.getTodo.select &
Omit<ReturnType<typeof weakMapMemoize>, ''>
>(exampleApi.endpoints.getTodo.select)

expect(exampleApi.endpoints.getTodo.select.resultsCount).toBeTypeOf(
'function',
)
expect(exampleApi.endpoints.getTodo.select.resetResultsCount).toBeTypeOf(
'function',
)
expect(exampleApi.endpoints.getTodo.select.clearCache).toBeTypeOf(
'function',
)

const firstResult = exampleApi.endpoints.getTodo.select('1')

exampleApi.endpoints.getTodo.select.clearCache()

const secondResult = exampleApi.endpoints.getTodo.select('1')

expect(firstResult).not.toBe(secondResult)

expect(firstResult(store.store.getState())).not.toBe(
secondResult(store.store.getState()),
)
})
it('uses createSelector instance memoize', () => {
const createLruSelector = createSelectorCreator(lruMemoize)
const createApi = buildCreateApi(
coreModule({ createSelector: createLruSelector }),
reactHooksModule({ createSelector: createLruSelector }),
)

const exampleLruApi = createApi({
baseQuery: fetchBaseQuery({
baseUrl: 'https://jsonplaceholder.typicode.com',
}),
endpoints: (build) => ({
getTodos: build.query<Todos, void>({
query: () => '/todos',
}),
getTodo: build.query<Todo, string>({
query: (id) => `/todos/${id}`,
}),
}),
})

expect(exampleLruApi.endpoints.getTodo.select('1')).toBe(
exampleLruApi.endpoints.getTodo.select('1'),
)

expect(exampleLruApi.endpoints.getTodo.select('1')).not.toBe(
exampleLruApi.endpoints.getTodo.select('2'),
)

const firstResult = exampleLruApi.endpoints.getTodo.select('1')

const secondResult = exampleLruApi.endpoints.getTodo.select('2')

const thirdResult = exampleLruApi.endpoints.getTodo.select('1')

// cache size of 1
expect(firstResult).not.toBe(thirdResult)
})
})