I'm trying to prevent the user from liking photos more than once when refreshing the page.
So the current incorrect flow is: click like on desired photo > number increments > refresh the page > click like on desired photo > number increments > refresh the page > *rinse & repeat*
The correct flow should be: click like on desired photo > number increments > refresh the page > click like on desired photo > number decrements > *rinse & repeat*
I know I'll need to map the liked UserID
s into local storage so that the browser remembers which photos were liked but I'm not sure how.
One of my many, many attempts in the else{}
block is below. I've completely hit a wall and not sure how to achieve this.
Note: using localstorage is not new to me as you can see I'm using it for something unrelated in the return()
. However, this mapping stuff to localstorage is what has me stumped.
useEffect(() => {
const headers = {
"Accept": 'application/json',
"Authorization": `Bearer ${authToken}`
};
axios.get('http://127.0.0.1:8000/api/get-user-uploads-data', {headers})
.then(resp => {
console.log(resp.data);
setGridData(resp.data);
}).catch(err => {
console.log(err);
});
}, []);
const handleLikesBasedOnUserId = (likedPhotoUserId, userName) => {
let mapOfLikes = {};
if(userLikedPhotos[likedPhotoUserId]) {
// dislike
delete userLikedPhotos[likedPhotoUserId];
gridData.find(photo => photo.UserID === likedPhotoUserId).likes--;
handleDislike(likedPhotoUserId, userName); // Send dislike incrementation via POST request
// localstorage logic?
} else {
// like
userLikedPhotos[likedPhotoUserId] = true;
gridData.find(photo => photo.UserID === likedPhotoUserId).likes ;
// attempt below
mapOfLikes[likedPhotoUserId] = mapOfLikes[likedPhotoUserId] ?? 1;
localStorage.setItem('mapOfLikes', JSON.stringify(mapOfLikes));
handleLike(likedPhotoUserId, userName); // Send like incrementation via POST request
// localstorage logic?
}
// Spread the userLikedPhotos to create a new object and force a rendering
setUserLikedPhotos({...userLikedPhotos});
};
return(
{
gridData.map((photos, index) => {
<span className="likesAmt">❤️ {photos.likes}</span><br/><Button variant="success" onClick={() => handleLikesBasedOnUserId(photos.UserID, photos.name)}>Like</Button><br/><span className="name">{photos.name} {localStorage.getItem('UserID') === photos.UserID ? <h6 className="you">(You)</h6> : null}</span>
})
}
);
CodePudding user response:
let UserLikedImageList
localStorage.hasOwnProperty(mapOfLikes)?
UserLikedImageList = json.parse(localStorage.getItem(mapOfLikes))
and map the ArrayList UserLikedImageList
CodePudding user response:
if (localStorage.hasOwnProperty(mapOfLikes) {
// dislikes logic
localStorage.deletItem('mapOfLikes')
else {
// likes logic
localStorage.setItem('mapOfLikes', json.stringify(mapOflikes)