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

Refactor around missing dependency in Link Control internal value sync effect #49509

Merged
merged 4 commits into from
May 4, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
42 changes: 42 additions & 0 deletions packages/block-editor/src/components/link-control/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2235,6 +2235,48 @@ describe( 'Controlling link title text', () => {
screen.queryByRole( 'textbox', { name: 'Text' } )
).not.toBeInTheDocument();
} );

it( 'should reset state on value change', async () => {
const user = userEvent.setup();
const textValue = 'My new text value';
const mockOnChange = jest.fn();

const { rerender } = render(
<LinkControl
value={ selectedLink }
forceIsEditingLink
hasTextControl
onChange={ mockOnChange }
/>
);

await toggleSettingsDrawer( user );

const textInput = screen.queryByRole( 'textbox', { name: 'Text' } );

expect( textInput ).toBeVisible();

await user.clear( textInput );
await user.keyboard( textValue );

// Was originall title: 'Hello Page', but we've changed it.
scruffian marked this conversation as resolved.
Show resolved Hide resolved
rerender(
<LinkControl
value={ {
...selectedLink,
title: 'Something else',
} }
forceIsEditingLink
hasTextControl
onChange={ mockOnChange }
/>
);

// The text input should not be showing as the form is submitted.
expect( screen.queryByRole( 'textbox', { name: 'Text' } ) ).toHaveValue(
'Something else'
);
} );
} );

async function toggleSettingsDrawer( user ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@ export default function useInternalInputValue( value ) {
value || ''
);

// If the value prop changes, update the internal state.
useEffect( () => {
/**
* If the value changes then sync this
* back up with state.
*/
if ( value && value !== internalInputValue ) {
setInternalInputValue( value );
}
setInternalInputValue( ( prevValue ) => {
if ( value && value !== prevValue ) {
return value;
}

return prevValue;
} );
}, [ value ] );

return [ internalInputValue, setInternalInputValue ];
Expand Down