Skip to content
Merged
Changes from 1 commit
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
Next Next commit
useUploadMediaFromBlobURL: Prevent duplicate uploads in StrictMode
  • Loading branch information
Mamaduka committed May 28, 2024
commit bb81915533d6788c53a5647596e4e6aef21e26aa
9 changes: 9 additions & 0 deletions packages/block-library/src/utils/hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,18 @@ export function useCanEditEntity( kind, name, recordId ) {
*/
export function useUploadMediaFromBlobURL( args = {} ) {
const latestArgs = useRef( args );
const hasUploadStarted = useRef( false );
const { getSettings } = useSelect( blockEditorStore );

useLayoutEffect( () => {
latestArgs.current = args;
} );

useEffect( () => {
if ( hasUploadStarted.current ) {
return;
}

if (
! latestArgs.current.url ||
! isBlobURL( latestArgs.current.url )
Expand All @@ -55,6 +60,8 @@ export function useUploadMediaFromBlobURL( args = {} ) {
const { url, allowedTypes, onChange, onError } = latestArgs.current;
const { mediaUpload } = getSettings();

hasUploadStarted.current = true;

mediaUpload( {
filesList: [ file ],
allowedTypes,
Expand All @@ -65,10 +72,12 @@ export function useUploadMediaFromBlobURL( args = {} ) {

revokeBlobURL( url );
onChange( media );
hasUploadStarted.current = false;
},
onError: ( message ) => {
revokeBlobURL( url );
onError( message );
hasUploadStarted.current = false;
},
} );
}, [ getSettings ] );
Expand Down