Home > database >  how to see if id in array already exists in localstorage
how to see if id in array already exists in localstorage

Time:08-18

I have this function, it saves the request response in localStorage. but I would like that if the id already existed in the array it would not make the request again

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);

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

now as you can see in the image it is saving duplicate ids enter image description here

I tried a few ways but without success, it seems that I can't map each item in the array

CodePudding user response:

You are using || condition. That is a reason your Api always calls whether you have data or not.Like in Or condition If your one condition is true from both (cache?.data && cache?.exp > Date. now()) || (cache?.data && cache?.data.find(item => item.data.id === id)) then you can get into the if block.

CodePudding user response:

localStorage is key => value storage, for searching etc. is better IndexedDB. Docs: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API

  • Related