Fix invalid return callback ref warning (#37655)
* Fix invalid return in callback ref and add tests * Changelog
This commit is contained in:
parent
252c2593b2
commit
a02d0a8117
|
@ -0,0 +1,4 @@
|
|||
Significance: patch
|
||||
Type: fix
|
||||
|
||||
Fix invalid return callback ref warning
|
|
@ -23,6 +23,8 @@ jest.mock( 'react-visibility-sensor', () =>
|
|||
} )
|
||||
);
|
||||
|
||||
window.open = jest.fn();
|
||||
|
||||
describe( 'InboxNoteCard', () => {
|
||||
const note = {
|
||||
id: 1,
|
||||
|
|
|
@ -42,4 +42,17 @@ describe( 'useCallbackOnLinkClick hook', () => {
|
|||
userEvent.click( getByText( 'Button' ) );
|
||||
expect( callback ).not.toHaveBeenCalled();
|
||||
} );
|
||||
|
||||
it( 'should remove listener on unmount', () => {
|
||||
const listener = jest.fn();
|
||||
const { getByText, unmount } = render(
|
||||
<TestComp callback={ jest.fn() } />
|
||||
);
|
||||
const span = getByText( 'Some Text' );
|
||||
jest.spyOn( span, 'removeEventListener' ).mockImplementation(
|
||||
listener
|
||||
);
|
||||
unmount();
|
||||
expect( listener ).toHaveBeenCalledTimes( 1 );
|
||||
} );
|
||||
} );
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { useCallback } from '@wordpress/element';
|
||||
import { useCallback, useEffect, useRef } from '@wordpress/element';
|
||||
|
||||
export function useCallbackOnLinkClick( onClick: ( link: string ) => void ) {
|
||||
const onNodeClick = useCallback(
|
||||
|
@ -20,17 +20,21 @@ export function useCallbackOnLinkClick( onClick: ( link: string ) => void ) {
|
|||
[ onClick ]
|
||||
);
|
||||
|
||||
return useCallback(
|
||||
( node: HTMLElement ) => {
|
||||
const nodeRef = useRef< HTMLElement | null >( null );
|
||||
|
||||
useEffect( () => {
|
||||
const node = nodeRef.current;
|
||||
if ( node ) {
|
||||
node.addEventListener( 'click', onNodeClick );
|
||||
}
|
||||
return () => {
|
||||
if ( node ) {
|
||||
node.addEventListener( 'click', onNodeClick );
|
||||
node.removeEventListener( 'click', onNodeClick );
|
||||
}
|
||||
return () => {
|
||||
if ( node ) {
|
||||
node.removeEventListener( 'click', onNodeClick );
|
||||
}
|
||||
};
|
||||
},
|
||||
[ onNodeClick ]
|
||||
);
|
||||
};
|
||||
}, [ onNodeClick ] );
|
||||
|
||||
return useCallback( ( node: HTMLElement ) => {
|
||||
nodeRef.current = node;
|
||||
}, [] );
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue