如何在Redux Toolkit的createApi查询端点中添加console.log日志?
Let's fix your issue step by step. The problem with your original code is that your query arrow function uses curly braces but doesn't explicitly return the request path — RTK Query needs that return value to know what endpoint to hit, which is why you're getting a compilation error.
Simple Solution: Log Directly in the query Function
You can add your console.log inside the query function, just make sure to explicitly return the endpoint path. Here's the corrected code:
export const pokemonApi = createApi({ reducerPath: 'pokemonApi', baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }), endpoints: (builder) => ({ getPokemonByName: builder.query<Pokemon, string>({ query: (name) => { // Add your log here console.log('Hello I am here!'); // Explicitly return the request path return `pokemon/${name}`; }, }), }), })
This works because the query function now properly returns the endpoint string after executing your log statement. Every time your component calls getPokemonByName, this log will fire right before the request is sent.
Advanced Option: Use onQueryStarted for Full Request Lifecycle Logs
If you want more detailed logging (like tracking when the request starts, succeeds, or fails), RTK Query provides the onQueryStarted hook. This is great for debugging the entire request flow:
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}`, async onQueryStarted(name, { queryFulfilled }) { console.log(`Fetching pokemon: ${name}`); try { const { data } = await queryFulfilled; console.log(`Successfully fetched ${name}! Data:`, data); } catch (error) { console.log(`Failed to fetch ${name}. Error:`, error); } } }), }), })
With this approach, you'll get logs at every stage of the request, which can be super helpful if you need to debug not just whether the endpoint was called, but also how the request progresses.
Why Your Original Code Failed
Your initial code had an invalid arrow function structure:
query: (name) => {`pokemon/${name}`, console.log('Hello I am here!')}
When you use curly braces with an arrow function, you have to use return to send back a value. Without that return, the query function returns undefined, which RTK Query can't use to build a request — hence the compilation error.
内容的提问来源于stack exchange,提问作者signed digital

