Fix invalid return callback ref warning (#37655)

* Fix invalid return in callback ref and add tests

* Changelog
This commit is contained in:
Ilyas Foo 2023-04-13 23:16:45 +08:00 committed by GitHub
parent 252c2593b2
commit a02d0a8117
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 35 additions and 12 deletions

View File

@ -0,0 +1,4 @@
Significance: patch
Type: fix
Fix invalid return callback ref warning

View File

@ -23,6 +23,8 @@ jest.mock( 'react-visibility-sensor', () =>
} )
);
window.open = jest.fn();
describe( 'InboxNoteCard', () => {
const note = {
id: 1,

View File

@ -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 );
} );
} );

View File

@ -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;
}, [] );
}