Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix block ref when multiple useBlockProps hooks are called #31906

Merged
merged 3 commits into from
May 19, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
* WordPress dependencies
*/
import {
useCallback,
useContext,
useLayoutEffect,
useMemo,
useRef,
useState,
} from '@wordpress/element';
import { useRefEffect } from '@wordpress/compose';

/**
* Internal dependencies
Expand All @@ -29,21 +29,24 @@ export function useBlockRefProvider( clientId ) {
const { refs, callbacks } = useContext( BlockRefs );
const ref = useRef();
useLayoutEffect( () => {
refs.set( clientId, ref );
refs.set( ref, clientId );
return () => {
refs.delete( clientId );
refs.delete( ref );
};
}, [] );
return useCallback( ( element ) => {
// Update the ref in the provider.
ref.current = element;
// Call any update functions.
callbacks.forEach( ( id, setElement ) => {
if ( clientId === id ) {
setElement( element );
}
} );
}, [] );
}, [ clientId ] );
return useRefEffect(
( element ) => {
// Update the ref in the provider.
ref.current = element;
// Call any update functions.
callbacks.forEach( ( id, setElement ) => {
if ( clientId === id ) {
setElement( element );
}
} );
},
[ clientId ]
);
}

/**
Expand All @@ -63,7 +66,17 @@ function useBlockRef( clientId ) {
return useMemo(
() => ( {
get current() {
return refs.get( freshClientId.current )?.current || null;
let element = null;

// Multiple refs may be created for a single block. Find the
// first that has an element set.
for ( const [ ref, id ] of refs.entries() ) {
if ( id === freshClientId.current && ref.current ) {
ntsekouras marked this conversation as resolved.
Show resolved Hide resolved
element = ref.current;
}
}

return element;
},
} ),
[]
Expand Down