File size: 1,528 Bytes
f3a9ef2
93dd66e
 
 
f3a9ef2
93dd66e
f3a9ef2
 
 
 
 
 
 
93dd66e
 
 
 
 
 
f3a9ef2
 
 
 
 
 
93dd66e
 
 
 
f3a9ef2
 
 
 
93dd66e
 
 
 
 
 
 
 
f3a9ef2
 
 
 
 
 
 
 
 
93dd66e
f3a9ef2
 
 
 
 
 
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
51
52
53
54
55
56
57
58
import { useAtom } from 'jotai';
import { DropzoneOptions, useDropzone } from 'react-dropzone';
import { DatasetImageEntity, datasetAtom } from '../../state';
import { toast } from 'react-hot-toast';

const useImageUpload = (options?: Partial<DropzoneOptions>) => {
	const [, setTarget] = useAtom(datasetAtom);
	const { getRootProps, getInputProps, isDragActive } = useDropzone({
		accept: {
			'image/*': ['.jpeg', '.png'],
		},
		multiple: true,
		onDrop: acceptedFiles => {
			if (acceptedFiles.length > 10) {
				toast('You can only upload 10 images max.', {
					icon: '⚠️',
				});
			}
			acceptedFiles.slice(0, 10).forEach(file => {
				try {
					const reader = new FileReader();
					reader.onloadend = () => {
						const newImage = reader.result as string;
						setTarget(prev => {
							// Check if the image already exists in the state
							if (
								prev.length >= 10 ||
								prev.find(entity => entity.url === newImage)
							) {
								// If it does, return the state unchanged
								return prev;
							} else {
								// If it doesn't, add the new image to the state
								return [
									...prev,
									{
										url: newImage,
										selected: false,
										name: `i-${prev.length + 1}`,
									} satisfies DatasetImageEntity,
								];
							}
						});
					};
					reader.readAsDataURL(file);
				} catch (err) {
					console.error(err);
				}
			});
		},
		...options,
	});

	return { getRootProps, getInputProps, isDragActive };
};

export default useImageUpload;