I'm trying to store all the likedUserIds
s and dislikedUserIds
s in local storage but for some reason, it's not even hitting the if()
statement. The likedPhotoUserId
function parameter indeed has a value, so why's it not hitting the first if()
?
Any feedback would be appreciated!
const handleLikesBasedOnUserId = (likedPhotoUserId) => {
console.log(likedPhotoUserId); // value is present
// dislike
if(likedPhotoUserId) {
// if the user id exists
if(localStorage.getItem('dislikedUserIds')) {
console.log("inside if");
// split the existing values into an array
let vals = localStorage.getItem('dislikedUserIds').split(',');
// if the value has not already been added
if (!vals.includes(likedPhotoUserId)) {
// add the value to the array
vals.push(likedPhotoUserId);
// sort the array
vals.sort();
// join the values into a delimeted string and store it
localStorage.setItem('dislikedUserIds', vals.join(','));
} else {
console.log("inside else");
// the key doesn't exist yet, add it and the new value
localStorage.setItem('dislikedUserIds', likedPhotoUserId);
}
}
} else {
// like
if(likedPhotoUserId) {
// if the user id exists
if(localStorage.getItem('likedUserIds')) {
console.log("inside if");
// split the existing values into an array
let vals = localStorage.getItem('likedUserIds').split(',');
// if the value has not already been added
if (!vals.includes(likedPhotoUserId)) {
// add the value to the array
vals.push(likedPhotoUserId);
// sort the array
vals.sort();
// join the values into a delimeted string and store it
localStorage.setItem('likedUserIds', vals.join(','));
} else {
console.log("inside else");
// the key doesn't exist yet, add it and the new value
localStorage.setItem('likedUserIds', likedPhotoUserId);
}
}
}
}
};
CodePudding user response:
If I don't misunderstand, you could do this in a more readable way:
function likeOrDislike(likedPhotoId) {
// Get value or define empty
const likedStored = localStorage.getItem("likedIds") || "[]";
// Convert string into array
let likedArray = JSON.parse(likedStored);
// Check if exists or not
if (likedArray.includes(likedPhotoId)) {
// Remove from array
likedArray = likedArray.filter(
(photo) => photo !== likedPhotoId
);
} else {
// Add to Array
likedArray.push(likedPhotoId);
}
// Convert to string to store in localStorage
const stringLiked = JSON.stringify(likedArray);
localStorage.setItem("likedIds", stringLiked);
}
CodePudding user response:
I'm having a lot of trouble understanding the logic in your code, but I'm pretty sure this satisfies your use-case. The issue with your code never hitting the first condition is particularly confusing because that doesn't happen in my test.
// when repeating strings in code, it's useful to set them
// as variables so your autocomplete and linter can help you out
const likedStorageKey = 'likedUserIds'
const dislikedStorageKey = 'dislikedUserIds'
// using JSON is a little easier than manually building and splitting the list
const storageListOrDefault = (key) =>
JSON.parse(localStorage.getItem(key)) || []
const setStorageItem = (key, list) =>
localStorage.setItem(key, JSON.stringify(list))
// if an item is in the list, remove it
const removeFromOppositeList = (storageKey, toRemove) => {
const vals = storageListOrDefault(storageKey)
setStorageItem(storageKey, vals.filter((id) => id !== toRemove))
}
const toggleInList = (storageKey, toAdd) => {
const vals = storageListOrDefault(storageKey)
// here we filter the old list, assuming you want your like/dislike
// buttons to have a 'neutral' state.
// if the array already includes the item and you're toggling to a neutral
// state, we remove the id
// if the list doesn't include the id, we concat the id to the array, and sort
const newList = vals.includes(toAdd)
? vals.filter((x) => x === toAdd)
: [...vals, toAdd].sort()
setStorageItem(storageKey, newList)
}
// onClick functions for your like and dislike buttons
const handleLike = (id) => {
if (id) {
removeFromOppositeList(dislikedStorageKey, id)
toggleInList(likedStorageKey, id)
}
}
const handleDislike = (id) => {
if (id) {
removeFromOppositeList(likedStorageKey, id)
toggleInList(dislikedStorageKey, id)
}
}
Performance note: none of this is particularly efficient, but if you're worried about performance I would recommend using a library that's designed for this sort of state management with persistence.