Как сохранять в sessionStorage несколько значений по 1 ключу
Как сохранять в sessionStorage несколько значений по 1 ключу
const nameBrands = JSON.parse(sessionStorage.getItem(subsProductsBrandPopupKey));
const name = [brand.name];
if (!nameBrands) {
sessionStorage.setItem(subsProductsBrandPopupKey, JSON.stringify(name));
}
const findName = nameBrands.find((item: string) => (item === brand.name));
if (findName) {
sendPopupBrandsLikesEvent('show');
setIsOpenPopup(true);
} else {
nameBrands.push(brand.name);
sessionStorage.setItem(subsProductsBrandPopupKey, JSON.stringify(nameBrands));
}
sessionStorage.getItem(subsProductsBrandPopupKey)
вот здесь выдает ошибку TS2345: Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'.
Ответы (1 шт):
Автор решения: Александр Рогонов
→ Ссылка
Не до конца понятно, что вы тут делаете.
const nameBrands = JSON.parse(sessionStorage.getItem(subsProductsBrandPopupKey));
Насколько я вижу, проблема в этой строчке. sessionStorage.getItem возвращает string | null а JSON.parse принимает только string.
Если по простому, то вот такая конструкция должна вас спасти.
const nameBrands = JSON.parse(sessionStorage.getItem(subsProductsBrandPopupKey) || '[]');