🚑 fix: resolve missing data in infinite queries (#2852)

* An issue where the InfiniteQuery was missing data
* Post add/delete operations, inconsistencies between client-side data structures and the database could lead to data being missed or duplicated.
* To address this, implemented normalization of client data following add/delete operations.
* performed refetching of data in the last page when necessary to ensure consistency.
This commit is contained in:
Yuichi Oneda 2024-05-24 09:38:38 -07:00 committed by GitHub
parent 35ba4ba1a4
commit 4369e75ca7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 294 additions and 28 deletions

View file

@ -65,6 +65,40 @@ export const deleteData = <TCollection, TData>(
// Delete the data from its current page
newData.pages[pageIndex][collectionName].splice(index, 1);
}
return newData;
};
/**
* Normalize the data so that the number of data on each page is within pageSize
*/
export const normalizeData = <TCollection, TData>(
data: InfiniteData<TCollection>,
collectionName: string,
pageSize: number,
): InfiniteData<TCollection> => {
const infiniteData = JSON.parse(JSON.stringify(data)) as InfiniteData<TCollection>;
const pageCount = infiniteData.pages.length;
if (pageCount === 0) {
return infiniteData;
}
const pageParams = infiniteData.pageParams;
// Combine all conversations of all pages into one array
const collection = infiniteData.pages.flatMap((page) => page[collectionName]);
if (collection.length === 0) {
return infiniteData;
}
// Create the restructured pages
const restructuredPages = Array.from({ length: pageCount }, (_, i) => ({
...infiniteData.pages[i],
[collectionName]: collection.slice(i * pageSize, (i + 1) * pageSize),
})).filter((page) => page[collectionName].length > 0); // Remove empty pages
return {
pageParams: pageParams.slice(0, restructuredPages.length),
pages: restructuredPages,
};
};