Leonardo Lima
Leonardo Lima

Reputation: 358

how to save an array in localstorage

I currently have this code, it saves in localstorage, but it generates several objects, I would like to store everything in a single array

getItemById(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 = {};

cache = JSON.parse(localStorage.getItem(key));

return (cache?.data && (cache?.exp > Date.now())) ?
  of(cache.data) :
  request.pipe(tap(v => {
    localStorage.setItem(key, JSON.stringify({data: v, exp: (Date.now() + msToExpire)}));
  }));
}

enter image description here

This code works, but I wanted to join all the StoreService_getItemById_, with this code it makes the array in a single StoreService_getItemById_, if you notice the image has several local storage with the name StoreService_getItemById_, I would like it to have only one and inside that it had the objects in array format

        localStorage.setItem(key, JSON.stringify({data: [v], exp: (Date.now() + msToExpire)}));

I wish it were the same "item" enter image description here

enter image description here

Upvotes: 1

Views: 965

Answers (1)

Chris Hamilton
Chris Hamilton

Reputation: 10954

It sounds like you want to append items to an array in local storage. The thing is, local storage only saves strings. You can parse the string to convert it into an array, append a new item, then overwrite the old string.

const key = 'my-array-key';
const someData = { name: 'name', id: 'abcdef' };
const msToExpire = 5000;

// Convert string to array, initializes empty array if string is empty
let arr: any[] = [];
let string = localStorage.getItem(key);
if (string) arr = JSON.parse(string);

// Push a new item and overwrite the old string
arr.push({data: someData, exp: (Date.now() + msToExpire)});
localStorage.setItem(key, JSON.stringify(arr));

I'm not really sure how you want to structure that function but this example should give you the general idea.

Upvotes: 3

Related Questions