Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

228
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda