Repository navigation
[RTK Query] Geting the inferred type from injectedQueryAPI #5264
Replies: 4 comments
|
you can import types from the store file, as the import should be removed during compilation |
|
A clean solution here is to import the type only from the store file: import type { AppDispatch } from '@/store'
export async function runLoader(dispatch: AppDispatch) {
const result = await dispatch(
injectedQueryAPI.endpoints.someEndpoint.initiate(arg)
)
if ('data' in result) {
return result.data
}
}Because it is And in your store file: export type AppDispatch = typeof store.dispatchIf you want a looser fallback that doesn't reference the store module at all, you can also use RTK's thunk dispatch type: import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit'
type AnyAppDispatch = ThunkDispatch<any, any, UnknownAction>But if this code is always called with your real So yes: |
This comment was marked as spam.
This comment was marked as spam.
|
To avoid circular dependencies between your API slice and the root store while maintaining type safety, you can extract the dispatch and state types using RTK's built-in utility types: import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit'
import type { RootState } from './store' // or define a minimal State interface
// 1. Typed dispatch without importing the concrete store instance:
export type AppDispatch = ThunkDispatch<RootState, unknown, UnknownAction>
// 2. Alternatively, extract the specific initiate trigger return type:
export type InjectedEndpointTrigger = ReturnType<
typeof injectedQueryAPI.endpoints.someEndpoints.initiate
>
export const someFunction = async (
dispatch: AppDispatch
) => {
const result = await dispatch(
injectedQueryAPI.endpoints.someEndpoints.initiate()
).unwrap()
return result
}Using |
Uh oh!
There was an error while loading. Please reload this page.
I'm curious about the type (dispatch, store) of the injected query api.
I can't import the root store because of the
no-circular-importruleAll reactions