简体   繁体   中英

how to see if id in array already exists in localstorage

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 在此处输入图像描述

I tried a few ways but without success, it seems that I can't map each item in the array the console.log(cache) 在此处输入图像描述

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM