Search code examples
javascriptreactjsexpressreduxsequelize.js

Prevent multiple fast clicks from triggering API


For my project a instagram-clone, I have a like and dislike button. If there are no likes or dislikes from the current logged in user, both will show black. If I like the post the like will show blue, and then when I click dislike, it switches from like to dislike, from blue to red. And clicking which ever is activated like/dislike it will unlike or undislike. The problem that arises, is that when you click super fast it somehow breaks through and adds multiple likes, when each user should only be able to add one like or one dislike.

enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here


Solution

  • Rate limiting example using Debouncing. If the user clicks fast multiple times only the last click will register. You can change the delay time as per your requirements.

    const debounce = (fn, delay) => {
      let t = null;
      return function(...args) {
        clearTimeout(t);
        t = setTimeout(() => {
          fn(...args);
        }, delay);
      }
    };
    
    let handleLike = () => {
      console.log("Like Clicked");
    };
    
    handleLike = debounce(handleLike, 1000);
    
    const btn = document.querySelector("#like");
    btn.addEventListener("click", handleLike);
    <button id="like">
      Like
    </button>