Skip to content

Commit

Permalink
Added a debounce to fix button mashing for article reactions (#174)
Browse files Browse the repository at this point in the history
  • Loading branch information
braydoncoyer committed Jun 26, 2022
1 parent 75af887 commit 6f953d7
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,5 @@ $ npm run dev
Create a `.env` file similar to `.env.example` and include the appropriate keys.

## Notion Article Template
Duplicate [the following Notion database](https://www.notion.so/0d3e00c6bbe54231897b9fcbc7747f78?v=4d7f0006d9a144b5bd8b9251f2ec39cd), grab the database ID and add it to the environment variables in the `.env` file.

Duplicate [the following Notion database](https://www.notion.so/0d3e00c6bbe54231897b9fcbc7747f78?v=4d7f0006d9a144b5bd8b9251f2ec39cd), grab the database ID and add it to the environment variables in the `.env` file.
9 changes: 7 additions & 2 deletions components/Reactions.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import useArticleReactions from '@/hooks/useArticleReactions';
import { useDebounce } from '@/lib/hooks/useDebounce';

const Reactions = ({ slug }) => {
const {
Expand Down Expand Up @@ -65,15 +66,19 @@ const Reactions = ({ slug }) => {
export default Reactions;

function ReactionCard({ isActive, incrementCB, decrementCB, children }) {
const handleClick = useDebounce(
isActive ? () => decrementCB() : () => incrementCB(),
300
);
return (
<div
role="button"
onClick={isActive ? () => decrementCB() : () => incrementCB()}
onClick={handleClick}
className={`${
isActive
? 'bg-gray-300 dark:bg-darker'
: 'bg-blueGray-100 dark:bg-midnight'
} flex-1 py-4 rounded-lg flex flex-col items-center general-ring-state`}
} flex-1 py-4 rounded-lg flex flex-col items-center general-ring-state select-none`}
>
{children}
</div>
Expand Down
25 changes: 25 additions & 0 deletions lib/hooks/useDebounce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import React, { Ref, useEffect, useRef, useState } from 'react';

export const useDebounce = (callback, delay) => {
const latestCallback = useRef(null);
const [lastCalledAt, setLastCalledAt] = useState(null);

useEffect(() => {
latestCallback.current = callback;
}, [callback]);

useEffect(() => {
if (lastCalledAt) {
const fire = () => {
setLastCalledAt(null);
latestCallback.current();
};

const fireAt = lastCalledAt + delay;
const id = setTimeout(fire, fireAt - Date.now());
return () => clearTimeout(id);
}
}, [lastCalledAt, delay]);

return () => setLastCalledAt(Date.now());
};

1 comment on commit 6f953d7

@vercel
Copy link

@vercel vercel bot commented on 6f953d7 Jun 26, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.