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

213
Visualizações
how to map repeated id in localstorage

I have this code, its idea is to save the product in localstorage and when the product is already in localstorage it doesn't make the request again

  getItemById(id) {
    // return this.http.get(`${environment.API_URL}item/getById/${id}`);
    return this.cacheS.getOrSetCache(`StoreService_getItemById_${id}_${this.layout.emp.id}`,  this.http.get(`${environment.API_URL}item/getById/${id}`), 300000);
 }


  getOrSetCache(key: string, request: Observable<any>, msToExpire = 3600000): Observable<any> {
    let cache: any = {};
    const keyy = 'StoreService_getItemById_teste';
    cache = JSON.parse(localStorage.getItem(keyy));

    return (cache?.data && (cache?.exp > Date.now())) ?
    of(cache.data) :
    request.pipe(
        tap(v => {
          let arr: any[] = [];
          let string = localStorage.getItem(keyy);
          if (string) arr = JSON.parse(string);
          console.log(arr)

          arr.push({data: v, exp: (Date.now() + msToExpire)});
          localStorage.setItem(keyy, JSON.stringify(arr));
       })
    );
}

how could i map the ids so that when i already have it in localstorage it doesn't make the request for that id ?

also wanted to know how I could see about the expiration date if the current time is equal to or greater than this timestamp, it removes it from the cache and does the query again

enter image description here in the image you can see that it has two repeated ids

enter image description here

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

After you parse the local storage item, use javascript find to check if the array already contains the ID.

getItemById(id) {
        // return this.http.get(`${environment.API_URL}item/getById/${id}`);
        return this.cacheS.getOrSetCache(
            id,
            `StoreService_getItemById_${id}_${this.layout.emp.id}`,
            this.http.get(`${environment.API_URL}item/getById/${id}`),
            300000
        );
    }

    getOrSetCache(
        id: any,
        key: string,
        request: Observable<any>,
        msToExpire = 3600000
    ): Observable<any> {
        let cache: any = {};
        const keyy = 'StoreService_getItemById_teste';
        cache = JSON.parse(localStorage.getItem(keyy));
        return (cache?.data && cache?.exp > Date.now()) ||
            (cache?.data && cache?.data.find(item => item.data.id === id))
            ? of(cache.data)
            : request.pipe(
                    tap(v => {
                        let arr: any[] = [];
                        let string = localStorage.getItem(keyy);
                        if (string) arr = JSON.parse(string);
                        console.log(arr);

                        arr.push({ data: v, exp: Date.now() + msToExpire });
                        localStorage.setItem(keyy, JSON.stringify(arr));
                    })
              );
    }
about 4 years ago · Santiago Trujillo Relatório
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