RTK查询如何得到X-Total-Countheader?
How to get X-Total-Count header with RTK Query?
请求后不知道如何访问headers。 Documentation 个不使用 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}`,
}),
}),
});
我像这样将它们放入组件中
const { data: guitarData } = useGetAllGuitarsQuery(searchingParams);
在哪里可以访问响应 headers?
你可以使用transformResponse
,它有签名
transformResponse?(
baseQueryReturnValue: BaseQueryResult<BaseQuery>,
meta: BaseQueryMeta<BaseQuery>,
arg: QueryArg
): ResultType | Promise<ResultType>
如果您使用 fetchBaseQuery
,meta
将是
type FetchBaseQueryMeta = { request: Request; response?: Response }
所以你可以这样写你的端点:
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')) }
}
}),
}),
});
请求后不知道如何访问headers。 Documentation 个不使用 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}`,
}),
}),
});
我像这样将它们放入组件中
const { data: guitarData } = useGetAllGuitarsQuery(searchingParams);
在哪里可以访问响应 headers?
你可以使用transformResponse
,它有签名
transformResponse?(
baseQueryReturnValue: BaseQueryResult<BaseQuery>,
meta: BaseQueryMeta<BaseQuery>,
arg: QueryArg
): ResultType | Promise<ResultType>
如果您使用 fetchBaseQuery
,meta
将是
type FetchBaseQueryMeta = { request: Request; response?: Response }
所以你可以这样写你的端点:
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')) }
}
}),
}),
});