Fileupload.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import * as React from 'react';
  2. import { FormError } from 'components/common/Input/Input.styled';
  3. import { InputLabel } from 'components/common/Input/InputLabel.styled';
  4. import { ErrorMessage } from '@hookform/error-message';
  5. import { useFormContext } from 'react-hook-form';
  6. import ControlledInput from 'components/common/Input/ControlledInput';
  7. import { Button } from 'components/common/Button/Button';
  8. import * as S from 'widgets/ClusterConfigForm/ClusterConfigForm.styled';
  9. import { useAppConfigFilesUpload } from 'lib/hooks/api/appConfig';
  10. const Fileupload: React.FC<{ name: string; label: string }> = ({
  11. name,
  12. label,
  13. }) => {
  14. const upload = useAppConfigFilesUpload();
  15. const id = React.useId();
  16. const { watch, setValue } = useFormContext();
  17. const loc = watch(name);
  18. const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
  19. if (e.target.files) {
  20. const formData = new FormData();
  21. const file = e.target.files[0];
  22. formData.append('file', file);
  23. const resp = await upload.mutateAsync(formData);
  24. setValue(name, resp.location, {
  25. shouldValidate: true,
  26. shouldDirty: true,
  27. });
  28. }
  29. };
  30. const onReset = () => {
  31. setValue(name, '', { shouldValidate: true, shouldDirty: true });
  32. };
  33. return (
  34. <div>
  35. <InputLabel htmlFor={id}>{label}</InputLabel>
  36. {loc ? (
  37. <S.FlexRow>
  38. <S.FlexGrow1>
  39. <ControlledInput name={name} disabled />
  40. </S.FlexGrow1>
  41. <Button buttonType="secondary" buttonSize="L" onClick={onReset}>
  42. Reset
  43. </Button>
  44. </S.FlexRow>
  45. ) : (
  46. <S.FileUploadInputWrapper>
  47. {upload.isLoading ? (
  48. <p>Uploading...</p>
  49. ) : (
  50. <input type="file" onChange={handleFileChange} />
  51. )}
  52. </S.FileUploadInputWrapper>
  53. )}
  54. <FormError>
  55. <ErrorMessage name={name} />
  56. </FormError>
  57. </div>
  58. );
  59. };
  60. export default Fileupload;