From 284b29531f1e3df8f24fe4d3f63e4b75a116820b Mon Sep 17 00:00:00 2001 From: Andrey Morozov Date: Wed, 6 Mar 2019 14:39:59 -0500 Subject: [PATCH] fix(docz): add window check to useWindowSize hook --- core/docz/src/hooks/useWindowSize.ts | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/core/docz/src/hooks/useWindowSize.ts b/core/docz/src/hooks/useWindowSize.ts index 97d7a0e39..52b0fe271 100644 --- a/core/docz/src/hooks/useWindowSize.ts +++ b/core/docz/src/hooks/useWindowSize.ts @@ -1,16 +1,26 @@ import { useState, useEffect } from 'react' import { throttle } from 'lodash/fp' -const getSize = () => ({ - innerHeight: window.innerHeight, - innerWidth: window.innerWidth, - outerHeight: window.outerHeight, - outerWidth: window.outerWidth, +const isClient = typeof window === 'object' + +const getSize = (initialWidth: number, initialHeight: number) => ({ + innerHeight: isClient ? window.innerHeight : initialHeight, + innerWidth: isClient ? window.innerWidth : initialWidth, + outerHeight: isClient ? window.outerHeight : initialHeight, + outerWidth: isClient ? window.outerWidth : initialWidth, }) -export const useWindowSize = () => { - const [windowSize, setWindowSize] = useState(getSize()) - const tSetWindowResize = throttle(300, () => setWindowSize(getSize())) +export const useWindowSize = ( + throttleMs: number = 300, + initialWidth = Infinity, + initialHeight = Infinity +) => { + const [windowSize, setWindowSize] = useState( + getSize(initialHeight, initialHeight) + ) + const tSetWindowResize = throttle(throttleMs, () => + setWindowSize(getSize(initialHeight, initialHeight)) + ) useEffect(() => { window.addEventListener('resize', tSetWindowResize)