Home > OS >  How can I get the number of likes to stay the same after the tab/browser has been closed?
How can I get the number of likes to stay the same after the tab/browser has been closed?

Time:10-06

enter image description here

this screenshot was taken after refreshing the page. I did not remove my like. but it shows that the number of likes is 0. It works perfectly fine without refreshing the page. The like button stays blue even after the page is refreshed. This is the code:

            <script>
                const likebtn = document.getElementById('likebtn');
                const currentURL = window.location.href;
                const likenum = document.getElementById('likenumber');
                const postarray = currentURL.split("/");
                const postName = postarray[4];

                function setLikeBtnColor() {
                    likebtn.style.color = JSON.parse(localStorage.getItem('likebtn')) ? 'cornflowerblue':'black';
                }
            
                setLikeBtnColor();

                async function current_color() {
                    const fetchData = await fetch('/hasliked/' postName)
                    .then(response => response.json())
                    .then(function newdata(data) {
                        let strdata = JSON.stringify(data)
                        let JSONdata = JSON.parse(strdata)
                        likenum.textContent = JSONdata.post_likes
                        return JSONdata.post_likes

                    })
                    return fetchData

                }

                async function set_color() {
                    const jsondata = await current_color()
                    if (jsondata['has_liked'] === true) {
                        likebtn.style.color = 'cornflowerblue'

                    } else {
                        likebtn.style.color = 'black'

                    }

        
                }
                

                async function getLikeNumber() {
                    const fetchData = await fetch('/postlikes/' postName)
                    .then(response => response.json())
                    .then(function getdata(data) {
                        let strdata = JSON.stringify(data)
                        let JSONdata = JSON.parse(strdata)
                        likenum.textContent = JSONdata.post_likes
                        return JSONdata.post_likes
                    })
                    return fetchData
                }

                async function displayLikes() {
                    let initialnum = await getLikeNumber()
                    likenum.innerHTML = initialnum
                }
                displayLikes()

                async function myFunction() {
                    localStorage.setItem('likebtn', !JSON.parse(localStorage.getItem('likebtn')));
                    setLikeBtnColor();
                    if (likebtn.style.color === 'cornflowerblue') {
                        let currentLikeNum = await getLikeNumber()
                        fetch('/postlikes/' postName, {
                            method:"POST",
                            body: JSON.stringify({
                                post_likes:currentLikeNum 1,
                                liked_post:postName,
                                is_liked:true
                            }),
                            headers:{
                                "Content-type":"application/json; charset=UTF-8"
                            }
                        })
                        likenum.innerHTML = currentLikeNum 1
                    } else {
                        let currentLikeNum = await getLikeNumber();
                        fetch('/postlikes/' postName, {
                            method:"POST",
                            body: JSON.stringify({
                                post_likes:currentLikeNum,
                                is_liked:false
                            }),
                            headers:{
                                "Content-type":"application/json; charset=UTF-8"
                            }
                        })
                        likenum.innerHTML = currentLikeNum
                    }};
                likebtn.addEventListener('click', myFunction);
                getlikenumber()
                
    
            </script>

This is the code for the backend:

@app.route('/postlikes/<string:post_name>', methods=["GET","POST"])
def postlikes(post_name):
    if request.method == "GET":
        print(request.method)
        post = Image.query.filter_by(post_name=post_name).first()
        return {"post_likes":post.likes}
    elif request.method == "POST":
        if current_user.is_authenticated:
            JSONdata = request.json
            post = Image.query.filter_by(post_name=post_name)
            post_1 = Image.query.filter_by(post_name=post_name).first()
            user = User.query.filter_by(username=current_user.username).first()
            if JSONdata['is_liked'] == True:
                liked_post = posts_liked_by_users(user_id=user.id,
                post_name=post_1.post_name
                )
                db.session.add(liked_post)
                db.session.commit()
                pass
            else:
                posts_liked_by_users.query.filter_by(post_name=post_1.post_name).delete()
                db.session.commit()
                
            
            for i in post:
                i.likes = JSONdata['post_likes']
        else:
            flash('You need to log in to like posts on this website.')
            return redirect(url_for('login'))

@app.route('/hasliked/<string:post_name>', methods=['GET','POST'])
def hasliked(post_name):
    post = Image.query.filter_by(post_name=post_name).first()
    user = User.query.filter_by(username=current_user.username).first()
    is_liked = posts_liked_by_users.query.filter_by(post_name=post_name).first()
    if is_liked.post_name == post.post_name and is_liked.user_id == user.id:
        return {"has_liked":True}
    else:
        return {"has_liked":False}

I will describe the problem more in detail. So when I click on the like button, the counter below it increments 1 to itself. This, however, only works as long as the user has not closed the tab or the browser. If the user closes the browser, the like button stays blue if the user did not remove their like but the counter is set back to the value that it had before this post was liked by the user, not including the like of the user. Again, it works if the user removes their like and likes it again, then the number in the counter is incremented by 1.

CodePudding user response:

You will need to persist the state of the application, either in a database or local-storage. This is usually done in a database, either directly or via an api endpoint. What framework your using, you did not say. It looks like Flask maybe.

db.session.add(value)

You are loosing the state of the component because closing the tab closes the session. All of your state is held in memory for that tab, when the tab closes the volatile memory is released. And any data allocated in it.

CodePudding user response:

The problem could be you are trying call an async function in main scope, when main scope is not async

try

                ...
                async function displayLikes() {
                    let initialnum = await getLikeNumber()
                    likenum.innerHTML = initialnum
                }
                //TRY THIS
                (async function() {
                     await displayLikes();
                })();

                async function myFunction() {
                     ....
  • Related