Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

227
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda