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

214
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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