new-personal-site/components/lib/hooks/useCustomEventDispatch.tsx
Benjamin Toby 8762e2da8d Updates
2025-03-27 07:37:16 +01:00

38 lines
858 B
TypeScript

import React from "react";
type Param = {
/**
* Custom Event Name
*/
name: string;
};
/**
* # Dispatch Custom Event
*/
export default function useCustomEventDispatch<
T extends { [key: string]: any } = { [key: string]: any }
>({ name }: Param) {
const dispatchCustomEvent = React.useCallback((value: T | string) => {
let dataParsed = typeof value == "object" ? value : undefined;
const str = typeof value == "string" ? value : undefined;
if (str) {
try {
dataParsed = JSON.parse(str);
} catch (error) {}
}
const event = new CustomEvent(name, {
detail: {
data: dataParsed,
message: str,
},
});
window.dispatchEvent(event);
}, []);
return { dispatchCustomEvent };
}