redux RTKQuery的dynamicBaseQuery未扩展终结点的url的问题

xqnpmsa8  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(123)

你好,我目前正在尝试将RTK查询添加到我的代码库中,使用拆分端点文件和动态baseUrl。https://redux-toolkit.js.org/rtk-query/usage/customizing-queries#constructing-a-dynamic-base-url-using-redux-state,以下是我目前为止所掌握的信息:

// baseApi.ts
const rawBaseQuery = fetchBaseQuery({
  baseUrl: "http://my-base-url/",
})

const dynamicBaseQuery: BaseQueryFn<
  string | FetchArgs,
  unknown,
  FetchBaseQueryError
> = async (args, api, extraOptions) => {
  const projectId = getProjectId();
  const projectVersion = await getProjectVersion(); //here is an async that fetches the version from the BE
  const adjustedUrl = `${projectId}/api/${projectVersion}`;
  const adjustedArgs = typeof args === 'string' ? adjustedUrl : { ...args, url: adjustedUrl };

  return rawBaseQuery(adjustedArgs, api, extraOptions);
}

export const baseApi = createApi({
  reducerPath: "base-api-reducer",
  baseQuery: dynamicBaseQuery,
  endpoints: () => ({}), // trying to do file split here
})

在一个单独的文件中,我实现了injectEndpoints,如下所示:

// data.ts
export const apiWithData = baseApi.injectEndpoints({
  endpoints: (build) => ({
    getAllData: build.query<Data[], void>({
      query: () => ({
        url: `${DATA_URL_SUFFIX}?any_other_query_param=true`
      })
    })
  }),
})

export const { useGetAllDataQuery } = apiWithData

当我在项目的Component.tsx中调用useGetAllDataQuery时,浏览器的“网络”选项卡显示一个网络请求,其URL以${projectVersion}结尾。预期的网络URL是“http://my-base-url/projectId 123/api/v1/data?any_other_query_param = true”,但实际的URL是“http://my-base-url/projectId 123/api/v1/",并且由于URL无效,请求以404结尾。
有什么想法是怎么回事?或任何我错过了添加。我检查了store.ts和一切都设置以下文件以及。

sirbozc5

sirbozc51#

我已经解决了这个问题。所以问题是我遗漏了一个额外的步骤。dynamicBaseQueryargs参数实际上来自端点。我需要用我的adjustedUrl来 Package 它,所以它看起来像这样:

const dynamicBaseQuery: BaseQueryFn<
  string | FetchArgs,
  unknown,
  FetchBaseQueryError
> = async (args, api, extraOptions) => {
  const projectId = getProjectId();
  const projectVersion = await getProjectVersion(); //here is an async that fetches the version from the BE

  // Updates
  const endpointUrl = typeof args === 'string' ? args : args.url;
  const adjustedUrl = `${projectId}/api/${projectVersion}/${endpointUrl}`;
  const adjustedArgs = typeof args === 'string' ? adjustedUrl : { ...args, url: adjustedUrl };

  return rawBaseQuery(adjustedArgs, api, extraOptions);
}

相关问题