我们必须使用一个 API,为所有端点添加特定值的前缀,例如:
GET /foo/<fooId>/post
GET /foo/<fooId>/post/<id>
GET /foo/<fooId>/authors
GET /foo/<fooId>/authors/<id>
客户端代码是使用 rtk-query-codegen-openapi 生成的,它会产生如下接口:
type GetFooByFooIdPostApiArg = {
fooId: string;
}
type GetFooByFooIdPostByPostIdApiArg = {
fooId: string;
id: string;
}
由于
fooId
值对于所有 API 调用都是通用的,我想避免在我们使用钩子的任何地方设置它:
// current
const {data} = useGetFooByFooIdPostByPostId({fooId: "..", id: "..."})
// desired
const {data} = useGetFooByFooIdPostByPostId({id: "..."})
有没有办法指定一个方法来检索
baseQuery
中的“fooId”,以便自动注入 fooId
参数? (假设它在 cookie/本地存储/redux 状态下可用)
您可以自定义创建 API 客户端时使用的基本查询。
基本示例:
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { selectFooId } from '../path/to/selectFooId';
const customBaseQuery = ({
baseUrl,
...baseQueryArgs
}) => (fetchArgs, api, extraOptions) => {
const fooId = selectFooId(api.getState());
// or read from localStorage/etc
if (!fooId) {
return {
error: {
data: "no foo id"
}
};
}
return fetchBaseQuery({
...baseQueryArgs,
baseUrl: `${baseUrl}/${fooId}`,
})(fetchArgs, api, extraOptions);
}
export const Api = createApi({
baseQuery: customBaseQuery({ baseUrl: "www.my-cool-site.com/foo" }),
endpoints: builder => ({ .... }),
});
请参阅 使用 Redux State 构建动态基本 URL ,了解一个很好的整体示例。