Skip to content

RTKQ How to access QueryArg in prepareHeaders() ? #3920

Answered by EskiMojo14
dhlavaty asked this question in Q&A
Discussion options

You must be logged in to vote

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

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@dhlavaty
Comment options

@markerikson
Comment options

Answer selected by dhlavaty
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants