reactjs createApi redux-toolkit中的日志记录

1sbrub3j  于 2023-06-05  发布在  React
关注(0)|答案(2)|浏览(235)

我想知道如何添加一个console.log

export const pokemonApi = createApi({
  reducerPath: 'pokemonApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
  endpoints: (builder) => ({
  getPokemonByName: builder.query<Pokemon, string>({
   query: (name) => `pokemon/${name}`,
    }),
  }),
})

这样当一个组件调用getPokemonByName时,它应该console.log('Hello,I am here!')
我已经尝试了下面,但不工作,并有编译错误。

getPokemonByName: builder.query<Pokemon, string>({
   query: (name) => {`pokemon/${name}`, **console.log('Hello I am here!')**}
    }),

https://redux-toolkit.js.org/rtk-query/api/createApi上没有此示例
我想这样做是因为我的组件试图调用这个方法,但我不确定它是否到达这里!

k2arahey

k2arahey1#

会是的

getPokemonByName: builder.query<Pokemon, string>({
   query: (name) => {
       console.log('Hello I am here!')
       return `pokemon/${name}`
     },
   }),

但你可能更应该使用Redux Devtools。
Redux Devtools有一个新的alpha版本,甚至支持RTK查询:https://chrome.google.com/webstore/detail/redux-devtools-next/oamphgegmigmlgkdnijmeomjenbmkbdg

yx2lnoni

yx2lnoni2#

观察redux的action payload将显示如下
{"type":"api/executeMutation/rejected","payload":{"status":"FETCH_ERROR","error":"TypeError: Network request failed"},"meta":{"baseQueryMeta":{"request":{"url":"http://localhost:4000/checkUserExist","credentials":"same-origin","headers":{"map":{"authorization":"","x-gapi-key":"xxxx-xx-xx-xxx-xxxx","content-type":"application/json"}},"method":"POST","mode":null,"signal":{},"referrer":null,"bodyUsed":false,"_bodyInit":"{\"Email\":\"xx@x.com\",\"PhoneNumber\":\"+xxxx\"}","_bodyText":"{\"Email\":\"xx@xx.com\",\"PhoneNumber\":\"+xxx\"}"}},"RTK_autoBatch":true,"arg":{"type":"mutation","endpointName":"checkUserExists","originalArgs":{"Email":"xx@xx.com","PhoneNumber":"+xxxx"},"track":true},"requestId":"FJke5ZaW-BYUdhRysxi98","rejectedWithValue":true,"requestStatus":"rejected","aborted":false,"condition":false},"error":{"message":"Rejected"}}
因此,您可以通过中间件访问它,如下所示

export const rtkQueryErrorLogger: Middleware =
  (api: MiddlewareAPI) => (next) => (action) => {
    console.log("RTK STrt-------------------R STrt");
    // console.log(
    //   {
    //     action: JSON.stringify(action),
    //     isPending: isPending(action),
    //     isRejected: isRejected(action),
    //     isRejectedWithValue: isRejectedWithValue(action),
    //   },
    //   "\n"
    // );
    if (action?.meta?.baseQueryMeta?.request)
      console.log(
        "API Request data",
        JSON.stringify({
          data: action?.meta?.baseQueryMeta?.request,
        })
      );

相关问题