|
| 1 | +import { useCallback, useEffect, useState } from 'react' |
| 2 | +import { ReadError } from '@iqss/dataverse-client-javascript' |
| 3 | +import { DataverseInfoRepository } from '../repositories/DataverseInfoRepository' |
| 4 | +import { JSDataverseReadErrorHandler } from '@/shared/helpers/JSDataverseReadErrorHandler' |
| 5 | +import { getAvailableDatasetMetadataExportFormats } from '../useCases/getAvailableDatasetMetadataExportFormats' |
| 6 | +import { DatasetMetadataExportFormats } from '../models/DatasetMetadataExportFormats' |
| 7 | + |
| 8 | +interface useGetAvailableDatasetMetadataExportFormatsProps { |
| 9 | + dataverseInfoRepository: DataverseInfoRepository |
| 10 | + autoFetch?: boolean |
| 11 | +} |
| 12 | + |
| 13 | +export const useGetAvailableDatasetMetadataExportFormats = ({ |
| 14 | + dataverseInfoRepository, |
| 15 | + autoFetch = true |
| 16 | +}: useGetAvailableDatasetMetadataExportFormatsProps) => { |
| 17 | + const [datasetMetadataExportFormats, setDatasetMetadataExportFormats] = |
| 18 | + useState<DatasetMetadataExportFormats | null>(null) |
| 19 | + const [isLoadingExportFormats, setIsLoadingExportFormats] = useState<boolean>(autoFetch) |
| 20 | + const [errorGetExportFormats, setErrorGetExportFormats] = useState<string | null>(null) |
| 21 | + |
| 22 | + const fetchDatasetMetadataExportFormats = useCallback(async () => { |
| 23 | + setIsLoadingExportFormats(true) |
| 24 | + setErrorGetExportFormats(null) |
| 25 | + |
| 26 | + try { |
| 27 | + const exportFormatsResponse = await getAvailableDatasetMetadataExportFormats( |
| 28 | + dataverseInfoRepository |
| 29 | + ) |
| 30 | + |
| 31 | + setDatasetMetadataExportFormats(exportFormatsResponse) |
| 32 | + } catch (err) { |
| 33 | + if (err instanceof ReadError) { |
| 34 | + const error = new JSDataverseReadErrorHandler(err) |
| 35 | + const formattedError = |
| 36 | + error.getReasonWithoutStatusCode() ?? /* istanbul ignore next */ error.getErrorMessage() |
| 37 | + |
| 38 | + setErrorGetExportFormats(formattedError) |
| 39 | + } else { |
| 40 | + setErrorGetExportFormats( |
| 41 | + 'Something went wrong getting the dataset export formats. Try again later.' |
| 42 | + ) |
| 43 | + } |
| 44 | + } finally { |
| 45 | + setIsLoadingExportFormats(false) |
| 46 | + } |
| 47 | + }, [dataverseInfoRepository]) |
| 48 | + |
| 49 | + useEffect(() => { |
| 50 | + if (autoFetch) { |
| 51 | + void fetchDatasetMetadataExportFormats() |
| 52 | + } |
| 53 | + }, [autoFetch, fetchDatasetMetadataExportFormats]) |
| 54 | + |
| 55 | + return { |
| 56 | + datasetMetadataExportFormats, |
| 57 | + isLoadingExportFormats, |
| 58 | + errorGetExportFormats, |
| 59 | + fetchDatasetMetadataExportFormats |
| 60 | + } |
| 61 | +} |
0 commit comments