Skip to content

Commit

Permalink
Fix block ref when multiple useBlockProps hooks are called
Browse files Browse the repository at this point in the history
  • Loading branch information
ellatrix committed May 17, 2021
1 parent a939c4f commit 5a39d56
Showing 1 changed file with 27 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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 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 ]
);
}

/**
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 ) {
element = ref.current;
}
}

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

0 comments on commit 5a39d56

Please sign in to comment.