Skip to content

Instantly share code, notes, and snippets.

@feliperohdee
Forked from KristofferEriksson/useShare.ts
Created February 9, 2024 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feliperohdee/9c8b1fe3d1609749728d8d49113b0f9d to your computer and use it in GitHub Desktop.
Save feliperohdee/9c8b1fe3d1609749728d8d49113b0f9d to your computer and use it in GitHub Desktop.
A React Typescript hook that let users share your content directly via native share dialogs
import { useCallback, useEffect, useState } from "react";
// Types for the useShare hook parameters
interface UseShareParams {
onShare?: (content: ShareParams) => void;
onSuccess?: (content: ShareParams) => void;
onError?: (error: any) => void;
fallback?: () => void;
successTimeout?: number;
}
// Types for the share function parameters
interface ShareParams {
title?: string;
text?: string;
url?: string;
}
const useShare = ({
onShare,
onSuccess,
onError,
fallback,
successTimeout = 3000,
}: UseShareParams) => {
const [isSupported, setIsSupported] = useState<boolean>(false);
const [isReady, setIsReady] = useState<boolean>(false);
const [isShared, setIsShared] = useState<boolean>(false);
// Check for Web Share API support
useEffect(() => {
if (typeof window !== "undefined" && "navigator" in window) {
setIsSupported("share" in navigator);
setIsReady(true);
}
}, []);
// Function to handle the reset of isShared state
const resetIsShared = (timeout: number) => {
const timer = setTimeout(() => setIsShared(false), timeout);
return () => clearTimeout(timer);
};
// Function to handle sharing or fallback
const share = useCallback(
async (content: ShareParams) => {
if (isSupported) {
// Execute onShare callback if provided
onShare?.(content);
try {
// Attempt to use the Web Share API
await navigator.share(content);
setIsShared(true);
// Execute onSuccess callback if provided
onSuccess?.(content);
// Reset isShared after the user-defined or default period of time
return resetIsShared(successTimeout);
} catch (error) {
// Execute onError callback if provided
onError?.(error);
}
} else {
// Execute fallback function if provided
fallback?.();
setIsShared(true);
// Reset isShared after the user-defined or default period of time
return resetIsShared(successTimeout);
}
},
[fallback, isSupported, onError, onShare, onSuccess, successTimeout],
);
return { share, isSupported, isReady, isShared };
};
export default useShare;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment