简体   繁体   English

尽管刷新浏览器,我怎样才能使同一用户不能两次喜欢照片?

[英]How can I make it so that the same user cannot like a photo twice despite refreshing browser?

I'm trying to figure out how I could simulate the same like system that exists on IG.我想弄清楚如何模拟 IG 上存在的相同系统。 For example: If the current logged in user likes a photo and then tries to like again, then it should dislike - and vice versa.例如:如果当前登录的用户喜欢一张照片,然后再次尝试喜欢,那么它应该不喜欢 - 反之亦然。 It doesn't matter if the user refreshes the page, logs out or clears browser cache since the liked data is coming from the server.用户刷新页面、注销或清除浏览器缓存都无关紧要,因为喜欢的数据来自服务器。

The useEffect() 's response that's being grabbed from the server looks like this:从服务器获取的useEffect()的响应如下所示:

{
  "url": "someUrl.com",
  "likes": 161,
  "UserID": "u-79696bbe-18e5-4e73-bfb7-e8c80b89e0a6",
  "name": "Paul",
  "photo_id": "p-a2bbb777-67de-4196-a92f-1effba006d13",
  "is_liked": 1,
  "user_id": "u-e6216642-5a01-4e69-913c-b2d19ef9b22e"
}
  • is_liked is 0 if the photo is disliked, 1 if it's liked如果不喜欢照片, is_liked为 0,如果喜欢,则为 1
  • UserID is the user's id of the photo that's been liked UserID是被点赞照片的用户id
  • user_id is any logged in user that liked the photo (I know it's confusing but I'll change the name later) user_id是喜欢照片的任何登录用户(我知道这很混乱,但我稍后会更改名称)
  • photo_id is id of the photo that's been liked photo_id是被点赞的照片的id

The handleLike() 's response that's being grabbed from the server looks like this.从服务器获取的handleLike()的响应如下所示。 It increments the total number of likes of the photo ( userLikes ) and toggles is_liked to 1它增加了照片的喜欢总数 ( userLikes ) 并将is_liked切换为 1

{
  "UserID": "u-79696bbe-18e5-4e73-bfb7-e8c80b89e0a6",
  "loggedInUserId": "u-43eaf8a2-2f47-4112-88f1-e08a382df59d",
  "likedPhotoId": "p-a2bbb777-67de-4196-a92f-1effba006d13",
  "userLikes": 163,
  "is_liked": 1
}

handleDislike() 's the opposite: handleDislike()相反:

{
    "UserID": "u-79696bbe-18e5-4e73-bfb7-e8c80b89e0a6",
    "loggedInUserId": "u-43eaf8a2-2f47-4112-88f1-e08a382df59d",
    "dislikedPhotoId": "p-a2bbb777-67de-4196-a92f-1effba006d13",
    "userLikes": 162,
    "is_liked": 0
}

In conclusion, how can I make it so that the like system is identical to Instagram's?总之,我怎样才能使 like 系统与 Instagram 的相同? The endpoints are returning the correct data but implementing on the frontend is where I'm totally stuck端点正在返回正确的数据,但在前端实现是我完全卡住的地方

Here's the code:这是代码:

const Grid = () => {
    let authToken                                                 = localStorage.getItem('token');

    const [gridData, setGridData]                                 = useState([]);
    const [userLikedPhotos, setUserLikedPhotos]                   = useState({});

    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, likedPhotoId, is_liked, user_id) => {
        if(userLikedPhotos[likedPhotoUserId]) {
            // dislike
            delete userLikedPhotos[likedPhotoUserId];
            gridData.find(photo => photo.UserID === likedPhotoUserId && photo.UserID !== user_id).likes--;
            handleDislike(likedPhotoUserId, userName, likedPhotoId);
        } else {
            // like
            userLikedPhotos[likedPhotoUserId] = true;
            gridData.find(photo => photo.UserID === likedPhotoUserId && photo.UserID !== user_id).likes++;
            handleLike(likedPhotoUserId, userName, likedPhotoId);
        }

        setUserLikedPhotos({...userLikedPhotos});
    };

    const handleLike = (likedPhotoUserId, userName, likedPhotoId) => {
        const url = 'http://127.0.0.1:8000/api/like';

        const headers = {
            "Accept": 'application/json',
            "Authorization": `Bearer ${authToken}`
        };

        let data = {
            'UserID': likedPhotoUserId,
            'userName' : userName,
            'likedPhotoId' : likedPhotoId
        };

        axios.post(url, data, {headers})
            .then(resp => {
                console.log(resp.data);
            }).catch(err => {
            console.log(err);
        });

    };

    const handleDislike = (likedPhotoUserId, userName, likedPhotoId) => {
        const url = 'http://127.0.0.1:8000/api/dislike';

        const headers = {
            "Accept": 'application/json',
            "Authorization": `Bearer ${authToken}`
        };

        let data = {
            'UserID': likedPhotoUserId,
            'userName' : userName,
            'dislikedPhotoId' : likedPhotoId
        };

        axios.post(url, data, {headers})
            .then(resp => {
                console.log(resp.data);
            }).catch(err => {
            console.log(err);
        });

    };

    return (
        <>
            <section className="gallery">
                <div className="container">
                    <div className="img-container">
                        {
                            gridData.map((photos, index) => {
                                return (
                                    <>
                                        <div className="userDetails">
                                            <span className="likesAmt">❤️ {photos.likes}</span>
                                            <Button variant="success" onClick={() => handleLikesBasedOnUserId(photos.UserID, photos.name, photos.photo_id, photos.is_liked, photos.user_id)}>Like</Button>
                                        </div>
                                    </>
                                )
                            })
                        }
                    </div>
                </div>
            </section>
        </>
    )
}

export default Grid;

I think you should set userLikedPhotos state with some of the value values grabbed from server in you useEffect and condition your buttons like this:我认为您应该使用从服务器获取的一些值设置 userLikedPhotos 状态 useEffect 并像这样调整您的按钮:

(userLikedPhotos?["is_liked"] ?
<Button>Dislike</Button>:
<Button>Like</Button>)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何确保不应在jquery中两次添加同一用户? - How can I make sure that same user shouldn't be added twice in jquery? 如何将我的 div 排列为 2 列,使其看起来像一个网格/照片库? - How can I arrange my divs in 2 columns so it looks like a grid/photo gallery? 如何让浏览器像 Facebook 一样记录点击? - How can I make a browser record the click like Facebook does? 如何做到这一点,以便我可以为提到的用户提供服务 - How to make it so that I can server deafen a mentioned user 如何收集用户提交的照片? - How can I collect a photo submitted by a user? 如何使浏览器显示“另存为对话框”,以便用户可以将字符串的内容保存到系统上的文件中? - How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system? 我怎样才能做到这一点,当用户输入一个字母时,输入会更改为下一个输入字段等等? - How can I make it so that when a user types a letter the input would change to the next input field and so on? 如何更改我的代码,以便用户只能喜欢该帖子一次? - How can I change my code so that the user can only like the post once? 如何在浏览器中加密用户活动信息使其无法被欺骗? - How to encrypt user activity information in the browser so it can't be spoofed? 如何在不刷新网站的情况下使这个时钟工作? - How can I make this clock working without refreshing website?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM