Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Fix useForcedLayout to re-select inner blocks after we manually insert one #6676

Merged
merged 4 commits into from
Oct 7, 2022
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
8 changes: 6 additions & 2 deletions assets/js/blocks/cart-checkout-shared/use-forced-layout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
useRef,
useCallback,
useMemo,
useState,
} from '@wordpress/element';
import { useSelect, useDispatch } from '@wordpress/data';
import {
Expand Down Expand Up @@ -41,6 +42,8 @@ export const useForcedLayout = ( {
} ): void => {
const currentRegisteredBlocks = useRef( registeredBlocks );
const currentDefaultTemplate = useRef( defaultTemplate );
const [ forcedBlocksInserted, setForcedBlocksInserted ] =
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping a count of inserted blocks feels a bit hacky here but I'm struggling to understand what we're trying to solve, why do we need to refresh the selectors after each block insert?

Copy link
Contributor Author

@opr opr Jul 13, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because this line:

is used to determine whether we need to insert the forced block. Since the selector isn't re-run, innerBlocks is still empty, despite it actually being updated in the previous run of this hook.

The alternative to tracking this number would be to remove the deps from the useSelect.

useState< number >( 0 );

const { insertBlock, replaceInnerBlocks } =
useDispatch( 'core/block-editor' );
Expand All @@ -55,15 +58,16 @@ export const useForcedLayout = ( {
),
};
},
[ clientId, currentRegisteredBlocks.current ]
[ clientId, currentRegisteredBlocks.current, forcedBlocksInserted ]
);

const appendBlock = useCallback(
( block, position ) => {
const newBlock = createBlock( block.name );
insertBlock( newBlock, position, clientId, false );
setForcedBlocksInserted( forcedBlocksInserted + 1 );
},
[ clientId, insertBlock ]
[ clientId, insertBlock, forcedBlocksInserted ]
);

const lockedBlockTypes = useMemo(
Expand Down