So I have a table that I'm currently lazy loading, and I want to cache the data of the 5 most current pages. When a user clicks the forward or backward button, I will send the pageNumber that they are going to, and the direction they are going(prev or next).
In my getData function, I will check if the page they are going to exists in a cachedData array or not. If yes, then I will dispatch that data without making an api call. If no, I will see the direction they are going to. For example, if they are going 1 -> 5, then page 6, I will remove page 1 from the cachedData array, then push page 6 in, and if they are going backward 6 -> 1, I will remove page 6, cuz it's the farthest from current page, and push page 1 instead. Below are the implementations:
const cachedData = [];
async function getData({ payload }) {
const { pageNumber, ...currentPageInfo } = payload;
const cachedPage = cachedData.find(page => page.pageNumber === pageNumber);
if (!cachedPage) {
const response = await fetchData(currentPageInfo);
if (response) {
if (cachedData.length >= 5) {
if (currentPageInfo.direction === "next") cachedData.shift();
cachedData.pop();
}
const { pageInfo, dataList } = response.data;
cachedData.push({
dataList,
pageNumber,
pageInfo,
});
cachedData.sort((x, y) => x.pageNumber - y.pageNumber);
dispatch(getDataSuccess({ res: dataList, pageInfo }));
}
} else {
dispatch(
getDataSuccess({
res: cachedPage.dataList,
pageInfo: cachedPage.pageInfo,
})
);
}
}
Currently it's working, but I'm not sure I'm on the right track. Between the shifting, sorting and finding, the performance aren't very good. The logic is weird because we are using our own way of pagination, and not the usual skip and take approach. But the important thing is whether anything can be improved in this code. Thank you very much.