69 lines
2.4 KiB
TypeScript
69 lines
2.4 KiB
TypeScript
import { useEffect, useState } from 'react';
|
|
import { backtestApiV2, type Backtest } from '@/features/backtest/services/backtestApiV2';
|
|
import { message } from './useExperimentSubmission';
|
|
|
|
const canonical = (value: Backtest) =>
|
|
value &&
|
|
typeof value.id === 'string' &&
|
|
typeof value.name === 'string' &&
|
|
!value.archivedAt &&
|
|
value.strategyVersionId &&
|
|
value.config &&
|
|
typeof value.config.canonical === 'object' &&
|
|
value.config.canonical !== null &&
|
|
typeof value.config.datasetHash === 'string';
|
|
|
|
export function useExperimentTemplates(initialBacktestId: string) {
|
|
const [backtests, setBacktests] = useState<Backtest[]>([]);
|
|
const [templateLoading, setTemplateLoading] = useState(true);
|
|
const [templateError, setTemplateError] = useState('');
|
|
const [templateReload, setTemplateReload] = useState(0);
|
|
const [limit, setLimit] = useState(50);
|
|
const [moreTemplates, setMoreTemplates] = useState(false);
|
|
useEffect(() => {
|
|
let current = true;
|
|
const controller = new AbortController();
|
|
setTemplateLoading(true);
|
|
setTemplateError('');
|
|
void (async () => {
|
|
const rows = await backtestApiV2.listBacktests(limit, 0, false, controller.signal);
|
|
if (!Array.isArray(rows)) {
|
|
throw new Error('The saved backtest list could not be read');
|
|
}
|
|
if (!current) {
|
|
return;
|
|
}
|
|
setMoreTemplates(rows.length === limit);
|
|
setBacktests(rows.filter(canonical));
|
|
if (initialBacktestId && !rows.some(item => item?.id === initialBacktestId)) {
|
|
// A missing linked template must not hide the successfully loaded catalog.
|
|
try {
|
|
const selected = await backtestApiV2.getBacktest(initialBacktestId);
|
|
if (current) {
|
|
setBacktests([...rows, selected].filter(canonical));
|
|
}
|
|
} catch (cause) {
|
|
if (current) {
|
|
setTemplateError(`Could not load the selected backtest: ${message(cause)}`);
|
|
}
|
|
}
|
|
}
|
|
})()
|
|
.catch(cause => {
|
|
if (current) {
|
|
setTemplateError(message(cause));
|
|
}
|
|
})
|
|
.finally(() => {
|
|
if (current) {
|
|
setTemplateLoading(false);
|
|
}
|
|
});
|
|
return () => {
|
|
current = false;
|
|
controller.abort();
|
|
};
|
|
}, [initialBacktestId, templateReload, limit]);
|
|
|
|
return { backtests, templateLoading, templateError, setTemplateReload, moreTemplates, setLimit };
|
|
}
|