RTK 查询:为baseQuery 中的每个端点分配默认参数

问题描述 投票:0回答:1

我们必须使用一个 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 状态下可用)

redux-toolkit rtk-query
1个回答
0
投票

您可以自定义创建 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 ,了解一个很好的整体示例。

© www.soinside.com 2019 - 2024. All rights reserved.