Custom Hook Call
const { data } = useListInfiniteQuery({
searchText: SearchText,
dateRange: dateRange,
select: getListItems,
});
Select Function
function getListItems({
pageParams,
pages,
}: InfiniteData<IListItems>): InfiniteData<IListItems> {
const allItems = pages.flatMap((page) => page.items);
const filterCount = transformFilterCount(pages[0]?.filterCount);// getting Error in this line
return {
pageParams,
pages: [
{
items: allItems,
filterCount,
},
],
};
}
Types and Transformation Function
export type FilterCountData = Record<string, Record<string, number>>;
export interface IFilterOption {
label: string;
count: number;
value: string;
}
export interface IFilterCategory {
name: string;
options: IFilterOption[];
}
function transformFilterCount(
filterCountData: FilterCountData | undefined,
): IFilterCategory[] {
if (!filterCountData) {
return [];
}
return Object.keys(filterCountData).map((key) => {
const options: IFilterOption[] = Object.keys(filterCountData[key]).map(
(subKey) => ({
label: filterSectionTitle[subKey.toLowerCase()] ?? subKey,
count: filterCountData[key][subKey] ?? 0,
value: subKey.toLowerCase(),
}),
);
return {
name: filterSectionTitle[key] ?? key,
options,
};
});
}
Error Message
Argument of type 'IFilterCategory[] | undefined' is not assignable to parameter of type 'FilterCountData | undefined'.
Type 'IFilterCategory[]' is not assignable to type 'FilterCountData'.
Index signature for type 'string' is missing in type 'IFilterCategory[]'.
Is it valid to transform the filterCount data from the API response into a different format within the select function of a in React Query? If so, how can I resolve the type error that I’m encountering during this transformation? Any guidance would be greatly appreciated.
API response
{
"Fruits": {
"apple": 93,
"Banana": 4,
"orange": 23
},
"Vegetable": {
"Carrot": 23,
"Beetroots": 23,
"tamato": 45
}
}
Desired Transformed Format
[
{
name: 'Fruits',
options: [
{ label: 'apple', count: 93, value: 'apple' },
{ label: 'Banana', count: 4, value: 'Banana' },
{ label: 'orange', count: 23, value: 'orange' },
]
},
{
name: 'Vegetable',
options: [
{ label: 'Carrot', count: 23, value: 'Carrot' },
{ label: 'Beetroots', count: 23, value: 'Beetroots' },
{ label: 'tamato', count: 45, value: 'tamato' },
]
}
];
Arpitha is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.