Skip to content

Commit

Permalink
Add useRandomUUID hook
Browse files Browse the repository at this point in the history
Change-type: minor
  • Loading branch information
Andrea Rosci authored and Andrea Rosci committed Nov 25, 2024
1 parent 78eb946 commit 52293a9
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/components/Form/Widgets/FileWidget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
faTrash,
faUpload,
} from '@fortawesome/free-solid-svg-icons';
import { useRandomUUID } from '../../../hooks/useRandomUUID';
import uniq from 'lodash/uniq';

const restingStyle: SxProps = {
Expand Down Expand Up @@ -135,8 +136,9 @@ export const FileWidget = ({
const [errorFiles, setErrorFiles] = useState<FileRejection[]>([]);
const theme = useTheme();
const mobile = useMediaQuery(theme.breakpoints.down('md'));
const formId = useRandomUUID();

const fileUploadId = useMemo(() => `file-upload-${crypto.randomUUID()}`, []);
const fileUploadId = useMemo(() => `file-upload-${formId}`, []);

const options = uiSchema?.['ui:options'] as UIOptions | undefined;
const accept = options?.accept;
Expand Down
16 changes: 16 additions & 0 deletions src/hooks/useRandomUUID.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { useMemo } from 'react';

export const useRandomUUID = (): string => {
const generateUUID = () => {
if (typeof crypto?.randomUUID === 'function') {
return crypto.randomUUID();
}

const template = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx';
return template.replace(/x/g, () =>
Math.floor(Math.random() * 16).toString(16),
);
};

return useMemo(() => generateUUID(), []);
};
1 change: 1 addition & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,5 @@ export * as Material from '@mui/material';
export * as MaterialLab from '@mui/lab';
export * as MaterialDataGrid from '@mui/x-data-grid';
export { enqueueSnackbar, closeSnackbar } from 'notistack';
export { useRandomUUID } from './hooks/useRandomUUID';
export * as designTokens from '@balena/design-tokens';

0 comments on commit 52293a9

Please sign in to comment.