如何在redux-toolkit中使用Createapi以外的basequery

发布于 2025-02-07 22:52:16 字数 1495 浏览 1 评论 0原文

为了减少我的应用程序大小,我想从redux-toolkit ynnc thunks中删除axios。另外,我想使用我的baseQuery函数,因为它具有我的应用程序的全局标题。

我当前的async thunk(使用axios):

export const loginAsyncThunk = createAsyncThunk<loginResponse, loginArgs>(
  'session/login',
  ({ username, password }) => new Promise((resolve, reject) => {
    axios.post(
      ROUTES.LOGIN(),
      { email: username, password }
    )
      .then((response) => resolve(response.data))
      .catch((error: AxiosError | typeof Error) => {
        if (axios.isAxiosError(error)) {
          reject(error.response?.data)
        }
        reject(error)
      })
  })
)

尝试用basequery实现它,我会遇到一个错误:

export const baseQuery = fetchBaseQuery({
  baseUrl: ROUTES.API_HOST,
  prepareHeaders: (headers, api) => {
    // app global headers
    headers.set('Content-Type', `application/json`)
    return headers
  },
})

export const loginAsyncThunk = createAsyncThunk<loginResponse, loginArgs>(
  'session/login',
  ({ username, password }) => new Promise((resolve, reject) => {
    const calledBaseQuery = baseQuery({
      url: ROUTES.LOGIN(),
      body: { email: username, password },
      // @ts-ignore: What should I do with following "api" and "extraOptions"?
    }, undefined, undefined)
    console.log(calledBaseQuery) // Promise {<rejected>: TypeError: Cannot read property 'signal' of undefined}
  })
)

In order to reduce my app size, I want to remove axios from my redux-toolkit async thunks. Also, I would like to use my baseQuery function, since it has the global headers of my application.

My current async thunk (using axios):

export const loginAsyncThunk = createAsyncThunk<loginResponse, loginArgs>(
  'session/login',
  ({ username, password }) => new Promise((resolve, reject) => {
    axios.post(
      ROUTES.LOGIN(),
      { email: username, password }
    )
      .then((response) => resolve(response.data))
      .catch((error: AxiosError | typeof Error) => {
        if (axios.isAxiosError(error)) {
          reject(error.response?.data)
        }
        reject(error)
      })
  })
)

Trying to implement it with baseQuery, I get an error:

export const baseQuery = fetchBaseQuery({
  baseUrl: ROUTES.API_HOST,
  prepareHeaders: (headers, api) => {
    // app global headers
    headers.set('Content-Type', `application/json`)
    return headers
  },
})

export const loginAsyncThunk = createAsyncThunk<loginResponse, loginArgs>(
  'session/login',
  ({ username, password }) => new Promise((resolve, reject) => {
    const calledBaseQuery = baseQuery({
      url: ROUTES.LOGIN(),
      body: { email: username, password },
      // @ts-ignore: What should I do with following "api" and "extraOptions"?
    }, undefined, undefined)
    console.log(calledBaseQuery) // Promise {<rejected>: TypeError: Cannot read property 'signal' of undefined}
  })
)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初雪 2025-02-14 22:52:17

您几乎不能 - 除非您自己构建api,否则我不会真正建议这样做,因为将来在任何时候api都可以获得其他属性。

老实说,我的问题是“为什么不让这个突变?”。您可以将匹配器添加到突变的 extrareducers 中的操作非常相似,就像您使用asyncthunk,因此,您的代码不会改变。

您可以看到,在此示例

extraReducers: (builder) => {
    builder.addMatcher(
      api.endpoints.login.matchFulfilled,
      (state, { payload }) => {
        state.token = payload.token
        state.user = payload.user
      }
    )
  },

You pretty much can't - unless you build api yourself, which I would not really recommend since in the future at any point api can get additional properties.

Honestly, my question the other way round would be "why don't you make this a mutation instead?". You can add matchers to a mutation's fulfilled action in extraReducers very similarly like you'd do with an asyncThunk, so not a lot of your code would change.

You can see that in this example:

extraReducers: (builder) => {
    builder.addMatcher(
      api.endpoints.login.matchFulfilled,
      (state, { payload }) => {
        state.token = payload.token
        state.user = payload.user
      }
    )
  },
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文