Using Custom Hook
const { data } = useListInfiniteQuery({
searchText: SearchText,
dateRange: dateRange,
select: getListItems,
});
List Transformation Function
function getListItems({
pageParams,
pages,
}: InfiniteData<IListItems>): InfiniteData<IListItems> {
const allItems = pages.flatMap((page) => page.items);
const filterCount = transformFilterCount(pages[0]?.filterCount);// Error occurs here
return {
pageParams,
pages: [
{
items: allItems,
filterCount,
},
],
};
}
Type Definitions 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 Details
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[]'.
Question: Can we modify the format of filterCount data from API response within the select function of React Query? If yes, how can we handle the encountered type error during this process? Appreciate any guidance on this issue.
API Response Sample
{
"Fruits": {
"apple": 93,
"Banana": 4,
"orange": 23
},
"Vegetable": {
"Carrot": 23,
"Beetroots": 23,
"tamato": 45
}
}
Expected 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' },
]
}
];