Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/eight-impalas-repair.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@stainless-code/react-custom-events": patch
---

add SSR support
3 changes: 0 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@ jobs:
release:
name: Release
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- name: Checkout branch
uses: actions/checkout@v4
Expand Down
8 changes: 5 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ type OmitFirstParam<T extends (...args: any[]) => any> = T extends (
? (...args: R) => Ret
: never;

const DOCUMENT = typeof document !== "undefined" ? document : undefined;

/**
* Creates a custom event with an associated React hook for listening.
*
Expand All @@ -25,7 +27,7 @@ export function createCustomEvent<Payload>(eventName: string) {
* @param {EventInit} [eventInitDict] - Additional options for the event.
*/
function dispatch(payload: Payload, eventInitDict?: EventInit) {
document.dispatchEvent(
DOCUMENT?.dispatchEvent(
new CustomEvent<Payload>(eventName, {
...eventInitDict,
detail: payload,
Expand Down Expand Up @@ -105,11 +107,11 @@ export function useCustomEventListener<Payload>(
}

onStartListening?.();
document.addEventListener(eventName, handleCallback);
DOCUMENT?.addEventListener(eventName, handleCallback);

return () => {
onStopListening?.();
document.removeEventListener(eventName, handleCallback);
DOCUMENT?.removeEventListener(eventName, handleCallback);
};
}, getDepList());
}