Skip to content

Commit

Permalink
Add loading state to Link component to prevent multiple clicks
Browse files Browse the repository at this point in the history
Since the link is often used as a button in the interface, we needed a way to prevent multiple clicks on it before the action is fully carried out.
  • Loading branch information
Adamik10 committed Jan 8, 2025
1 parent 5966224 commit 5014e7b
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/components/atoms/links/Link.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from "react";
import React, { useState } from "react";
import { getLinkHandler } from "./getLinkHandler";

export interface LinkProps {
Expand Down Expand Up @@ -28,6 +28,8 @@ const Link: React.FC<LinkProps> = ({
stopPropagation = false,
isHiddenFromScreenReaders
}) => {
const [isLoading, setIsLoading] = useState(false);

const handleClick = getLinkHandler({
type: "click",
isNewTab,
Expand All @@ -45,11 +47,20 @@ const Link: React.FC<LinkProps> = ({
});

const onclickHandler = onClick
? (
? async (
e:
| React.MouseEvent<HTMLAnchorElement>
| React.KeyboardEvent<HTMLAnchorElement>
) => onClick().then(() => handleClick(e))
) => {
if (isLoading) return; // Prevent further clicks
setIsLoading(true); // Set loading state to true
try {
await onClick(); // Await the provided onClick
handleClick(e); // Call handleClick after onClick resolves
} finally {
setIsLoading(false); // Reset loading state
}
}
: handleClick;

return (
Expand Down

0 comments on commit 5014e7b

Please sign in to comment.