File size: 1,655 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { useQueryClient } from '@tanstack/react-query';
import { createHigherOrderComponent } from '@wordpress/compose';
import { useTranslate } from 'i18n-calypso';
import { useCallback } from 'react';
import { useDispatch } from 'react-redux';
import { useDeleteMediaMutation } from 'calypso/data/media/use-delete-media-mutation';
import { deleteMedia as deleteMediaAction } from 'calypso/state/media/actions';
import { errorNotice, removeNotice } from 'calypso/state/notices/actions';

export const withDeleteMedia = createHigherOrderComponent(
	( Wrapped ) => ( props ) => {
		const queryClient = useQueryClient();
		const dispatch = useDispatch();
		const translate = useTranslate();
		const { mutateAsync } = useDeleteMediaMutation( {
			onSuccess( mediaItem, { siteId } ) {
				dispatch( deleteMediaAction( siteId, mediaItem.ID ) );
			},
		} );

		const deleteMedia = useCallback(
			async ( siteId, mediaIds ) => {
				dispatch( removeNotice( `delete-media-notice` ) );

				const promises = await Promise.allSettled(
					mediaIds.map( ( mediaId ) => mutateAsync( { siteId, mediaId } ) )
				);

				if ( promises.some( ( p ) => p.status === 'rejected' ) ) {
					dispatch(
						errorNotice( translate( 'We were unable to delete all of the selected media items.' ), {
							id: `delete-media-notice`,
						} )
					);
				}

				if ( promises.some( ( p ) => p.status === 'fulfilled' ) ) {
					queryClient.invalidateQueries( {
						queryKey: [ 'media-storage', siteId ],
					} );
				}
			},
			[ mutateAsync, dispatch, queryClient, translate ]
		);

		return <Wrapped { ...props } deleteMedia={ deleteMedia } />;
	},
	'WithDeleteMedia'
);