Skip to content

Commit

Permalink
Fix useBlockSync race condition (#23292)
Browse files Browse the repository at this point in the history
  • Loading branch information
youknowriad authored Jun 20, 2020
1 parent 9fae92f commit aaa0b32
Showing 1 changed file with 7 additions and 11 deletions.
18 changes: 7 additions & 11 deletions packages/block-editor/src/components/provider/use-block-sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ export default function useBlockSync( {
// waiting for React renders for changes.
const onInputRef = useRef( onInput );
const onChangeRef = useRef( onChange );
useEffect( () => {
onInputRef.current = onInput;
onChangeRef.current = onChange;
}, [ onInput, onChange ] );

useEffect( () => {
const {
getSelectionStart,
Expand All @@ -120,17 +125,7 @@ export default function useBlockSync( {
let isPersistent = isLastBlockChangePersistent();
let previousAreBlocksDifferent = false;

onInputRef.current = onInput;
onChangeRef.current = onChange;
const unsubscribe = registry.subscribe( () => {
// Sometimes, subscriptions might trigger with stale callbacks
// before they are cleaned up. Avoid running them.
if (
onInputRef.current !== onInput ||
onChangeRef.current !== onChange
)
return;

// Sometimes, when changing block lists, lingering subscriptions
// might trigger before they are cleaned up. If the block for which
// the subscription runs is no longer in the store, this would clear
Expand Down Expand Up @@ -184,8 +179,9 @@ export default function useBlockSync( {
}
previousAreBlocksDifferent = areBlocksDifferent;
} );

return () => unsubscribe();
}, [ registry, onChange, onInput, clientId ] );
}, [ registry, clientId ] );

// Determine if blocks need to be reset when they change.
useEffect( () => {
Expand Down

0 comments on commit aaa0b32

Please sign in to comment.