RTK查询 |使来自另一个 API 服务的 API 服务的缓存无效

RTK Query | Invalidate cache of an API service from another API service

我创建了多个 RTK 查询 API 服务,拆分成多个文件。对于这个问题,我有两个服务:“合同”和“属性”。合同服务应该能够在合同更新时使属性缓存失效,但即使在向合同服务提供“Properties”标签之后——缓存也不会失效。

这是我的设置:

属性:

export const propertyApi = createApi({
    reducerPath: 'propertyApi',
    baseQuery: fetchBaseQuery({ baseUrl: `${API_BASE_URL}/properties` }),
    tagTypes: ['Properties'],
    endpoints: builder => ({
        // many endpoints
    })
})

export const {
    // many hooks
} = propertyApi

合同:

export const contractApi = createApi({
    reducerPath: 'contractApi',
    baseQuery: fetchBaseQuery({ baseUrl: `${API_BASE_URL}/contracts` }),
    tagTypes: ['Contracts', 'Properties'],
    endpoints: builder => ({
        // ...
        modifyContract: builder.mutation<Contract, { contract: Partial<ContractDto>, contractId: Contract['id'], propertyId: Property['id'] }>({
            query: ({ contract, contractId }) => {
                return {
                    url: `/${contractId}`,
                    method: 'PATCH',
                    credentials: "include",
                    body: contract
                }
            },
            // to my understanding, this should invalidate the property cache for the property with 'propertyId', but it doesn't seem to work
            invalidatesTags: (_res, _err, { propertyId }) => ['Properties', 'Contracts', { type: 'Properties', id: propertyId }]
        })
    })
})

export const {
    // ...
    useModifyContractMutation
} = contractApi

商店设置:

export const STORE_RESET_ACTION_TYPE = 'RESET_STORE'

const combinedReducer = combineReducers({
    [photoApi.reducerPath]: photoApi.reducer,
    [authApi.reducerPath]: authApi.reducer,
    [propertyApi.reducerPath]: propertyApi.reducer,
    [cronApi.reducerPath]: cronApi.reducer,
    [contractApi.reducerPath]: contractApi.reducer,
    auth: authReducer
})

const rootReducer: Reducer = (state: RootState, action: AnyAction) => {
    if (action.type === STORE_RESET_ACTION_TYPE) {
        state = {} as RootState
    }
    return combinedReducer(state, action)
}

export const store = configureStore({
    reducer: rootReducer,
    middleware: (getDefaultMiddleware) => {
        return getDefaultMiddleware().concat([
            photoApi.middleware,
            authApi.middleware,
            propertyApi.middleware,
            cronApi.middleware,
            contractApi.middleware,
            errorHandlerMiddleware
        ])
    }
})

setupListeners(store.dispatch)

export type AppDispatch = typeof store.dispatch
export type RootState = ReturnType<typeof store.getState>
export type AppThunk<ReturnType = void> = ThunkAction<
    ReturnType,
    RootState,
    unknown,
    Action<string>
>

export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector

如果这些 api 服务具有相互依赖的数据(这有点暗示它们应该相互无效)它们不应该是多个 api 服务 - 它们实际上只是一个 api 的多个端点。我们在文档中的多个位置进行了说明。

引用 the quickstart tutorial 例如:

Typically, you should only have one API slice per base URL that your application needs to communicate with. For example, if your site fetches data from both /api/posts and /api/users, you would have a single API slice with /api/ as the base URL, and separate endpoint definitions for posts and users. This allows you to effectively take advantage of automated re-fetching by defining tag relationships across endpoints.

相反,如果您想将那个 api 拆分成多个文件,您可以这样做 - 使用文档中描述的 code splitting 机制。

这也意味着您不必在 configureStore 调用中添加很多 api 切片和中间件,只需添加一个即可。