Home > Net >  How to get X-Total-Count header with RTK Query?
How to get X-Total-Count header with RTK Query?

Time:12-19

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?

CodePudding user response:

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')) }
      }
    }),
  }),
});
  • Related