- Adjusted indentation and formatting in login, permissions, profile, and security pages for better readability. - Enhanced the clarity of conditional statements and function calls in permissions and profile components. - Updated type definitions in vite-env.d.ts for better code structure. - Cleaned up array mapping syntax in ProductTest.php for consistency.
87 lines
2.1 KiB
TypeScript
87 lines
2.1 KiB
TypeScript
import { useCallback, useState } from 'react';
|
|
import { uploadFile, UploadError } from '@/lib/upload';
|
|
|
|
type UploadState = {
|
|
uploading: boolean;
|
|
progress: number;
|
|
error: string | null;
|
|
key: string | null;
|
|
preview: string | null;
|
|
};
|
|
|
|
export function useFileUpload() {
|
|
const [state, setState] = useState<UploadState>({
|
|
uploading: false,
|
|
progress: 0,
|
|
error: null,
|
|
key: null,
|
|
preview: null,
|
|
});
|
|
|
|
const upload = useCallback(
|
|
async (file: File, folder?: string): Promise<string | null> => {
|
|
setState({
|
|
uploading: true,
|
|
progress: 0,
|
|
error: null,
|
|
key: null,
|
|
preview: null,
|
|
});
|
|
|
|
try {
|
|
const preview = URL.createObjectURL(file);
|
|
setState((prev) => ({ ...prev, preview, progress: 30 }));
|
|
|
|
const key = await uploadFile(file, folder);
|
|
setState((prev) => ({
|
|
...prev,
|
|
key,
|
|
uploading: false,
|
|
progress: 100,
|
|
}));
|
|
|
|
return key;
|
|
} catch (err) {
|
|
const message =
|
|
err instanceof UploadError
|
|
? err.message
|
|
: 'Terjadi kesalahan saat mengunggah file.';
|
|
setState((prev) => ({
|
|
...prev,
|
|
error: message,
|
|
uploading: false,
|
|
}));
|
|
|
|
return null;
|
|
}
|
|
},
|
|
[],
|
|
);
|
|
|
|
const reset = useCallback(() => {
|
|
setState({
|
|
uploading: false,
|
|
progress: 0,
|
|
error: null,
|
|
key: null,
|
|
preview: null,
|
|
});
|
|
}, []);
|
|
|
|
const setKey = useCallback((key: string | null) => {
|
|
setState((prev) => ({ ...prev, key }));
|
|
}, []);
|
|
|
|
const setPreview = useCallback((preview: string | null) => {
|
|
setState((prev) => ({ ...prev, preview }));
|
|
}, []);
|
|
|
|
return {
|
|
...state,
|
|
upload,
|
|
reset,
|
|
setKey,
|
|
setPreview,
|
|
};
|
|
}
|