Skip to content
This repository has been archived by the owner on May 6, 2024. It is now read-only.

Commit

Permalink
fix: make initial page visibility configurable (#26)
Browse files Browse the repository at this point in the history
Previously, the page visibility state was initialized from the `document.hidden` state. When server-rendering, `document` is `undefined` and throws an error. Instead, we assume the page is visible on load by default, and allow a custom initial value to be passed in so client-rendered apps can keep using `document.hidden`.
  • Loading branch information
connor-baer authored Oct 30, 2020
1 parent c47c7ba commit 5298376
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 13 deletions.
4 changes: 2 additions & 2 deletions src/hooks/usePageActiveTrigger/usePageActiveTrigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ import useBaseTrigger from '../useBaseTrigger';
import useVisibilityChange from '../useVisibilityChange';
import { Events } from '../../types';

const usePageActiveTrigger = () => {
const usePageActiveTrigger = (initial?: boolean) => {
const dispatch = useBaseTrigger(Events.pageView);

useVisibilityChange((isVisible) => isVisible && dispatch({}));
useVisibilityChange((isVisible) => isVisible && dispatch({}), initial);
};

export default usePageActiveTrigger;
9 changes: 2 additions & 7 deletions src/hooks/useVisibilityChange/useVisibilityChange.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,24 +26,19 @@ describe('useVisibilityChange', () => {
});

it('should execute the provided callback every time visibility changes with the current visibility as prop', () => {
Object.defineProperty(document, 'hidden', {
configurable: true,
value: true
});

const visibilityHandler = jest.fn();

renderHook(() => useVisibilityChange(visibilityHandler));

Object.defineProperty(document, 'hidden', {
configurable: true,
value: false
value: true
});

act(() => {
document.dispatchEvent(new Event('visibilitychange'));
});

expect(visibilityHandler).toHaveBeenCalledWith(true);
expect(visibilityHandler).toHaveBeenCalledWith(false);
});
});
9 changes: 5 additions & 4 deletions src/hooks/useVisibilityChange/useVisibilityChange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@ import * as React from 'react';

import usePrevious from '../usePrevious';

const useVisibilityChange = (callback: (isVisible: boolean) => void): void => {
const [documentVisibility, setDocumentVisibility] = React.useState(
!document.hidden
);
const useVisibilityChange = (
callback: (isVisible: boolean) => void,
initial = true
): void => {
const [documentVisibility, setDocumentVisibility] = React.useState(initial);
const previousVisibility = usePrevious(documentVisibility);

React.useEffect(() => {
Expand Down

0 comments on commit 5298376

Please sign in to comment.