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

我创建了多个 RTK 查询 API 服务,拆分成多个文件。对于这个问题,我有两个服务:“契约(Contract)”和“属性”。契约(Contract)服务应该能够在契约(Contract)更新时使属性缓存失效,但即使在向契约(Contract)服务提供“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

契约(Contract):

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 片段和中间件,只需添加一个即可。

https://stackoverflow.com/questions/69243083/

相关文章:

indexing - 为什么索引 HashMap 不返回引用?

node.js - express-session不设置cookie?

visual-studio-code - 如何在VSC终端创建文件?

angular - 延迟加载模块时构建错误

python - Linux Mint Cinnamon 错误打开设置(没有名为 'PIL' 的模块

assembly - 如果 x86 jmp 跳转到其他两个连续有效地址之间的地址会发生什么?

reactjs - 如何更改Chakra UI Toast组件的背景颜色?

reactjs - Material-UI:一个组件正在将 SwitchBase 不受控制的检查状态

ruby-on-rails - Rails 参数方法 : Why can it be accesse

java - 没有同步顺序的程序