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

warn for and migrate old options and require all hooks #3549

Merged
merged 3 commits into from
Oct 1, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 3 additions & 2 deletions errors.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,6 @@
"28": "Cannot refetch a query that has not been started yet.",
"29": "`builder.addCase` cannot be called with an empty action type",
"30": "`builder.addCase` cannot be called with two reducers for the same action type",
"31": "\"middleware\" field must be a callback"
}
"31": "\"middleware\" field must be a callback",
"32": "When using custom hooks for context, all hooks need to be provided: .\\nHook was either not provided or not a function."
}
140 changes: 88 additions & 52 deletions packages/toolkit/src/query/react/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,57 +140,93 @@ export const reactHooksModule = ({
useStore: rrUseStore,
},
unstable__sideEffectsInRender = false,
}: ReactHooksModuleOptions = {}): Module<ReactHooksModule> => ({
name: reactHooksModuleName,
init(api, { serializeQueryArgs }, context) {
const anyApi = api as any as Api<
any,
Record<string, any>,
string,
string,
ReactHooksModule
>
const { buildQueryHooks, buildMutationHook, usePrefetch } = buildHooks({
api,
moduleOptions: {
batch,
hooks,
unstable__sideEffectsInRender,
},
serializeQueryArgs,
context,
})
safeAssign(anyApi, { usePrefetch })
safeAssign(context, { batch })

return {
injectEndpoint(endpointName, definition) {
if (isQueryDefinition(definition)) {
const {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription,
} = buildQueryHooks(endpointName)
safeAssign(anyApi.endpoints[endpointName], {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription,
})
;(api as any)[`use${capitalize(endpointName)}Query`] = useQuery
;(api as any)[`useLazy${capitalize(endpointName)}Query`] =
useLazyQuery
} else if (isMutationDefinition(definition)) {
const useMutation = buildMutationHook(endpointName)
safeAssign(anyApi.endpoints[endpointName], {
useMutation,
})
;(api as any)[`use${capitalize(endpointName)}Mutation`] = useMutation
...rest
}: ReactHooksModuleOptions = {}): Module<ReactHooksModule> => {
if (process.env.NODE_ENV !== 'production') {
const hookNames = ['useDispatch', 'useSelector', 'useStore'] as const
let warned = false
for (const hookName of hookNames) {
// warn for old hook options
if (Object.keys(rest).length > 0) {
if ((rest as Partial<typeof hooks>)[hookName]) {
if (!warned) {
console.warn(
'As of RTK 2.0, the hooks now need to be specified as one object, provided under a `hooks` key:' +
'\n`reactHooksModule({ hooks: { useDispatch, useSelector, useStore } })`'
)
warned = true
}
}
},
// migrate
// @ts-ignore
hooks[hookName] = rest[hookName]
}
// then make sure we have them all
if (typeof hooks[hookName] !== 'function') {
throw new Error(
`When using custom hooks for context, all ${
hookNames.length
} hooks need to be provided: ${hookNames.join(
', '
)}.\nHook ${hookName} was either not provided or not a function.`
)
}
}
},
})
}

return {
name: reactHooksModuleName,
init(api, { serializeQueryArgs }, context) {
const anyApi = api as any as Api<
any,
Record<string, any>,
string,
string,
ReactHooksModule
>
const { buildQueryHooks, buildMutationHook, usePrefetch } = buildHooks({
api,
moduleOptions: {
batch,
hooks,
unstable__sideEffectsInRender,
},
serializeQueryArgs,
context,
})
safeAssign(anyApi, { usePrefetch })
safeAssign(context, { batch })

return {
injectEndpoint(endpointName, definition) {
if (isQueryDefinition(definition)) {
const {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription,
} = buildQueryHooks(endpointName)
safeAssign(anyApi.endpoints[endpointName], {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription,
})
;(api as any)[`use${capitalize(endpointName)}Query`] = useQuery
;(api as any)[`useLazy${capitalize(endpointName)}Query`] =
useLazyQuery
} else if (isMutationDefinition(definition)) {
const useMutation = buildMutationHook(endpointName)
safeAssign(anyApi.endpoints[endpointName], {
useMutation,
})
;(api as any)[`use${capitalize(endpointName)}Mutation`] =
useMutation
}
},
}
},
}
}
126 changes: 126 additions & 0 deletions packages/toolkit/src/query/tests/buildCreateApi.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import * as React from 'react'
import type { ReactReduxContextValue } from 'react-redux'
import {
createDispatchHook,
createSelectorHook,
createStoreHook,
Provider,
} from 'react-redux'
import {
buildCreateApi,
coreModule,
reactHooksModule,
} from '@reduxjs/toolkit/query/react'
import {
act,
fireEvent,
render,
screen,
waitFor,
renderHook,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { rest } from 'msw'
import {
actionsReducer,
ANY,
expectExactType,
expectType,
setupApiStore,
withProvider,
useRenderCounter,
waitMs,
} from './helpers'
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 { delay } from '../../utils'

const MyContext = React.createContext<ReactReduxContextValue>(null as any)

describe('buildCreateApi', () => {
test('Works with all hooks provided', async () => {
const customCreateApi = buildCreateApi(
coreModule(),
reactHooksModule({
hooks: {
useDispatch: createDispatchHook(MyContext),
useSelector: createSelectorHook(MyContext),
useStore: createStoreHook(MyContext),
},
})
)

const api = customCreateApi({
baseQuery: async (arg: any) => {
await waitMs()

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

let getRenderCount: () => number = () => 0

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

// Copy of 'useQuery hook basic render count assumptions' from `buildHooks.test.tsx`
function User() {
const { isFetching } = api.endpoints.getUser.useQuery(1)
getRenderCount = useRenderCounter()

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

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

render(<User />, { wrapper: Wrapper })
// By the time this runs, the initial render will happen, and the query
// will start immediately running by the time we can expect this
expect(getRenderCount()).toBe(2)

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

test("Throws an error if you don't provide all hooks", async () => {
const callBuildCreateApi = () => {
const customCreateApi = buildCreateApi(
coreModule(),
reactHooksModule({
// @ts-ignore
hooks: {
useDispatch: createDispatchHook(MyContext),
useSelector: createSelectorHook(MyContext),
},
})
)
}

expect(callBuildCreateApi).toThrowErrorMatchingInlineSnapshot(
`"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."`
)
})
})