How to get X-Total-Count header with RTK Query?
Asked Answered
D

1

7

Don't know how to access the headers after the request. Documentation examples without using x-total-count

const guitarApi = createApi({
  reducerPath: 'GUITARS',
  baseQuery: fetchBaseQuery({ baseUrl: API_URL }),
  endpoints: (builder) => ({
    getAllGuitars: builder.query<AllGuitarsResponse, number>({
      query: (limit = 1) => `${APIRoute.Guitars}_limit${limit}`,
    }),
  }),
});

I get them into the component like this

const { data: guitarData } = useGetAllGuitarsQuery(searchingParams);

Where can I access the response headers?

Downward answered 19/12, 2021 at 1:22 Comment(0)
C
16

You can use transformResponse for this, it has the signature

  transformResponse?(
    baseQueryReturnValue: BaseQueryResult<BaseQuery>,
    meta: BaseQueryMeta<BaseQuery>,
    arg: QueryArg
  ): ResultType | Promise<ResultType>

and if you use fetchBaseQuery, meta will be

type FetchBaseQueryMeta = { request: Request; response?: Response }

So you can write your endpoint like:

const guitarApi = createApi({
  reducerPath: 'GUITARS',
  baseQuery: fetchBaseQuery({ baseUrl: API_URL }),
  endpoints: (builder) => ({
    getAllGuitars: builder.query<{ apiResponse: AllGuitarsResponse, totalCount: number}, number>({
      query: (limit = 1) => `${APIRoute.Guitars}_limit${limit}`,
      transformResponse(apiResponse, meta) {
        return { apiResponse, totalCount: Number(meta.response.headers.get('X-Total-Count')) }
      }
    }),
  }),
});
Caucasia answered 19/12, 2021 at 8:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.