Skip to content

Commit 6f953d7

Browse files
authored
Added a debounce to fix button mashing for article reactions (#174)
1 parent 75af887 commit 6f953d7

File tree

3 files changed

+33
-3
lines changed

3 files changed

+33
-3
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,5 +35,5 @@ $ npm run dev
3535
Create a `.env` file similar to `.env.example` and include the appropriate keys.
3636

3737
## Notion Article Template
38-
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.
3938

39+
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.

components/Reactions.tsx

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import useArticleReactions from '@/hooks/useArticleReactions';
2+
import { useDebounce } from '@/lib/hooks/useDebounce';
23

34
const Reactions = ({ slug }) => {
45
const {
@@ -65,15 +66,19 @@ const Reactions = ({ slug }) => {
6566
export default Reactions;
6667

6768
function ReactionCard({ isActive, incrementCB, decrementCB, children }) {
69+
const handleClick = useDebounce(
70+
isActive ? () => decrementCB() : () => incrementCB(),
71+
300
72+
);
6873
return (
6974
<div
7075
role="button"
71-
onClick={isActive ? () => decrementCB() : () => incrementCB()}
76+
onClick={handleClick}
7277
className={`${
7378
isActive
7479
? 'bg-gray-300 dark:bg-darker'
7580
: 'bg-blueGray-100 dark:bg-midnight'
76-
} flex-1 py-4 rounded-lg flex flex-col items-center general-ring-state`}
81+
} flex-1 py-4 rounded-lg flex flex-col items-center general-ring-state select-none`}
7782
>
7883
{children}
7984
</div>

lib/hooks/useDebounce.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import React, { Ref, useEffect, useRef, useState } from 'react';
2+
3+
export const useDebounce = (callback, delay) => {
4+
const latestCallback = useRef(null);
5+
const [lastCalledAt, setLastCalledAt] = useState(null);
6+
7+
useEffect(() => {
8+
latestCallback.current = callback;
9+
}, [callback]);
10+
11+
useEffect(() => {
12+
if (lastCalledAt) {
13+
const fire = () => {
14+
setLastCalledAt(null);
15+
latestCallback.current();
16+
};
17+
18+
const fireAt = lastCalledAt + delay;
19+
const id = setTimeout(fire, fireAt - Date.now());
20+
return () => clearTimeout(id);
21+
}
22+
}, [lastCalledAt, delay]);
23+
24+
return () => setLastCalledAt(Date.now());
25+
};

0 commit comments

Comments
 (0)