Skip to content

Commit

Permalink
refactor: useLoadSpectra function return type
Browse files Browse the repository at this point in the history
  • Loading branch information
hamed-musallam committed Nov 14, 2023
1 parent f3d109b commit 751ec21
Showing 1 changed file with 32 additions and 27 deletions.
59 changes: 32 additions & 27 deletions src/hooks/useLoadSpectra.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,39 +45,44 @@ async function loadSpectraFromURLs(urls: string[]) {

type NMRiumData = NmriumState['data'];

export function useLoadSpectra() {
type LoadOptions = { urls: string[] } | { files: File[] };

interface UseLoadSpectraResult {
data: { version: number; data: NMRiumData };
load: (options: LoadOptions) => void;
isLoading: boolean;
}

export function useLoadSpectra(): UseLoadSpectraResult {
const [data, setData] = useState<NMRiumData>({ spectra: [], molecules: [] });
const [isLoading, setLoading] = useState<boolean>(false);

const load = useCallback(
async (options: { urls: string[] } | { files: File[] }) => {
setLoading(true);
try {
if ('urls' in options) {
if (isArrayOfString(options.urls)) {
const result = await loadSpectraFromURLs(options.urls);
setData(result as NMRiumData);
} else {
throw new Error('The input must be a valid urls array of string[]');
}
} else if ('files' in options) {
const result = await loadSpectraFromFiles(options.files);
if (result?.spectra) {
appendFilters(result?.spectra);
}
const load = useCallback(async (options: LoadOptions) => {
setLoading(true);
try {
if ('urls' in options) {
if (isArrayOfString(options.urls)) {
const result = await loadSpectraFromURLs(options.urls);
setData(result as NMRiumData);
} else {
throw new Error('The input must be a valid urls array of string[]');
}
} else if ('files' in options) {
const result = await loadSpectraFromFiles(options.files);
if (result?.spectra) {
appendFilters(result?.spectra);
}
} catch (error: unknown) {
const loadError = error as Error;
events.trigger('error', loadError);
// eslint-disable-next-line no-console
console.log(error);
} finally {
setLoading(false);
setData(result as NMRiumData);
}
},
[],
);
} catch (error: unknown) {
const loadError = error as Error;
events.trigger('error', loadError);
// eslint-disable-next-line no-console
console.log(error);
} finally {
setLoading(false);
}
}, []);

return useMemo(
() => ({
Expand Down

0 comments on commit 751ec21

Please sign in to comment.