-
Notifications
You must be signed in to change notification settings - Fork 103
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(useViewportRange): don't update state after unmount (#402)
- Loading branch information
1 parent
7aab047
commit 6b8daef
Showing
1 changed file
with
11 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,22 +1,22 @@ | ||
import { Device } from '@ui5/webcomponents-react-base/lib/Device'; | ||
import { useCallback, useEffect, useState } from 'react'; | ||
import { useEffect, useState, useRef } from 'react'; | ||
|
||
export const useViewportRange = (rangeSet) => { | ||
const [currentRange, setCurrentRange] = useState(Device.media.getCurrentRange(rangeSet, window.innerWidth).name); | ||
|
||
const onWindowResize = useCallback( | ||
({ name: range }) => { | ||
setCurrentRange(range); | ||
}, | ||
[setCurrentRange] | ||
); | ||
const isMounted = useRef(true); | ||
|
||
useEffect(() => { | ||
Device.media.attachHandler(onWindowResize, null, 'StdExt'); | ||
const handler = ({ name: range }) => { | ||
if (isMounted.current === true) { | ||
setCurrentRange(range); | ||
} | ||
}; | ||
Device.media.attachHandler(handler, null, 'StdExt'); | ||
return () => { | ||
Device.resize.detachHandler(onWindowResize, null); | ||
isMounted.current = false; | ||
Device.resize.detachHandler(handler, null); | ||
}; | ||
}, [onWindowResize]); | ||
}, [setCurrentRange, isMounted]); | ||
|
||
return currentRange; | ||
}; |