MadCcc
3 years ago
committed by
GitHub
5 changed files with 90 additions and 4 deletions
@ -0,0 +1,20 @@ |
|||
import { mount } from 'enzyme'; |
|||
import React from 'react'; |
|||
import useDestroyed from '../hooks/useDestroyed'; |
|||
|
|||
describe('useMounted', () => { |
|||
it('should work properly', () => { |
|||
let isDestroyed = null; |
|||
|
|||
const AutoUnmounted = () => { |
|||
isDestroyed = useDestroyed(); |
|||
|
|||
return <div>Mounted</div>; |
|||
}; |
|||
|
|||
const wrapper = mount(<AutoUnmounted />); |
|||
expect(isDestroyed()).toBeFalsy(); |
|||
wrapper.unmount(); |
|||
expect(isDestroyed()).toBeTruthy(); |
|||
}); |
|||
}); |
@ -0,0 +1,14 @@ |
|||
import * as React from 'react'; |
|||
|
|||
export default function useDestroyed() { |
|||
const mountedRef = React.useRef<boolean>(true); |
|||
|
|||
React.useEffect( |
|||
() => () => { |
|||
mountedRef.current = false; |
|||
}, |
|||
[], |
|||
); |
|||
|
|||
return () => !mountedRef.current; |
|||
} |
Loading…
Reference in new issue