Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

226
Views
How to cache a lazy load table without external library

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!