Skip to content

Commit

Permalink
MediaReplaceFlow: Fix UI showing stale URL by avoiding state duplicat…
Browse files Browse the repository at this point in the history
…ion (#42116)

* MediaReplaceFlow: Keep internal URL state synchronized

* Remove internal state in favor of mediaURL prop

* Tests: Ensure MediaReplaceFlow's mediaURL prop is controlled by wrapper
  • Loading branch information
mcsf authored Jul 5, 2022
1 parent 1c4dfcc commit 6465552
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* WordPress dependencies
*/
import { useState, useRef } from '@wordpress/element';
import { useRef } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { speak } from '@wordpress/a11y';
import {
Expand Down Expand Up @@ -55,7 +55,6 @@ const MediaReplaceFlow = ( {
addToGallery,
handleUpload = true,
} ) => {
const [ mediaURLValue, setMediaURLValue ] = useState( mediaURL );
const mediaUpload = useSelect( ( select ) => {
return select( blockEditorStore ).getSettings().mediaUpload;
}, [] );
Expand Down Expand Up @@ -88,7 +87,6 @@ const MediaReplaceFlow = ( {
onToggleFeaturedImage();
}
closeMenu();
setMediaURLValue( media?.url );
// Calling `onSelect` after the state update since it might unmount the component.
onSelect( media );
speak( __( 'The media file has been replaced' ) );
Expand Down Expand Up @@ -213,14 +211,13 @@ const MediaReplaceFlow = ( {
{ __( 'Current media URL:' ) }
</span>

<Tooltip text={ mediaURLValue } position="bottom">
<Tooltip text={ mediaURL } position="bottom">
<div>
<LinkControl
value={ { url: mediaURLValue } }
value={ { url: mediaURL } }
settings={ [] }
showSuggestions={ false }
onChange={ ( { url } ) => {
setMediaURLValue( url );
onSelectURL( url );
editMediaButtonRef.current.focus();
} }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,36 @@
*/
import { render, fireEvent } from '@testing-library/react';

/**
* WordPress dependencies
*/
import { useState } from '@wordpress/element';

/**
* Internal dependencies
*/
import MediaReplaceFlow from '../';

const noop = () => {};

function setUpMediaReplaceFlow() {
const { container } = render(
function TestWrapper() {
const [ mediaURL, setMediaURL ] = useState( 'https://example.media' );
return (
<MediaReplaceFlow
mediaId={ 1 }
mediaURL={ 'https://example.media' }
mediaURL={ mediaURL }
allowedTypes={ [ 'png' ] }
accept="image/*"
onSelect={ noop }
onSelectURL={ noop }
onSelectURL={ setMediaURL }
onError={ noop }
onCloseModal={ noop }
/>
);
}

function setUpMediaReplaceFlow() {
const { container } = render( <TestWrapper /> );
return container;
}

Expand Down

0 comments on commit 6465552

Please sign in to comment.