RTKQ How to access QueryArg
in prepareHeaders()
?
#3920
-
When using RTK Query, how can I safely access I need to implement OAuth's Resource and Scope Aware Authorization. TL;DR: For some API calls, I need to prepare a different Let's see a simplified example: const baseQuery = fetchBaseQuery({
baseUrl: '/',
prepareHeaders: async (headers, api) => {
let token;
if (api.endpoint === "deletePokemon") {
const { pokemonId } = api.queryArgs; // <-- How to get THIS
token = await getPokemonScopedOAuthToken(pokemonId);
} else {
token = await getGeneralOAuthToken();
}
headers.set('authorization', `Bearer ${token}`)
return headers
},
});
export const pokemonApi = createApi({
baseQuery,
endpoints: (builder) => ({
getPokemonByName: builder.query({
query: (pokemonId: string) => `pokemon/${pokemonId}`,
}),
deletePokemon: builder.mutation({
query: ({ pokemonId }) => ({
url: `pokemon/${pokemonId}`,
method: 'DELETE',
}),
}),
}),
}); I need to access |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
prepareHeaders has no access to the argument, you should instead do it in your query function: const baseQuery = fetchBaseQuery({
baseUrl: "/",
prepareHeaders: async (headers, api) => {
if (!headers.has("authorization")) {
const token = await getGeneralOAuthToken();
headers.set("authorization", `Bearer ${token}`);
}
return headers;
},
});
export const pokemonApi = createApi({
baseQuery,
endpoints: (builder) => ({
getPokemonByName: builder.query({
query: (pokemonId: string) => ({
url: `pokemon/${pokemonId}`,
headers: {
authorization: `Bearer ${getPokemonScopedOAuthToken(pokemonId)}`, // if we can do this synchronously
},
}),
}),
// if we can't do it synchronously, we need a queryFn
deletePokemon: builder.mutation({
queryFn: async ({ pokemonId }, api, extraOptions, fetchWithBQ) => {
try {
const token = await getPokemonScopedOAuthToken(pokemonId);
return fetchWithBQ({
url: `pokemon/${pokemonId}`,
method: "DELETE",
headers: {
authorization: `Bearer ${token}`,
},
});
} catch (e) {
return { error: { status: "CUSTOM_ERROR", data: e } };
}
},
}),
}),
}); |
Beta Was this translation helpful? Give feedback.
prepareHeaders has no access to the argument, you should instead do it in your query function: