-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathuseStdcmEnv.tsx
51 lines (43 loc) · 1.69 KB
/
useStdcmEnv.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { useCallback, useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { osrdEditoastApi } from 'common/api/osrdEditoastApi';
import { useOsrdConfActions } from 'common/osrdContext';
import type { StdcmConfSliceActions } from 'reducers/osrdconf/stdcmConf';
export const NO_CONFIG_FOUND_MSG = 'No configuration found';
export default function useStdcmEnvironment() {
const dispatch = useDispatch();
const { updateStdcmEnvironment } = useOsrdConfActions() as StdcmConfSliceActions;
const [getStdcmSearchEnvironment] =
osrdEditoastApi.endpoints.getStdcmSearchEnvironment.useLazyQuery();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<null | Error>(null);
const loadStdcmEnvironment = useCallback(async () => {
try {
setError(null);
setLoading(true);
const { data } = await getStdcmSearchEnvironment();
if (!data) throw new Error(NO_CONFIG_FOUND_MSG);
dispatch(
updateStdcmEnvironment({
infraID: data.infra_id,
timetableID: data.timetable_id,
electricalProfileSetId: data.electrical_profile_set_id,
workScheduleGroupId: data.work_schedule_group_id,
temporarySpeedLimitGroupId: data.temporary_speed_limit_group_id,
searchDatetimeWindow: {
begin: new Date(data.search_window_begin),
end: new Date(data.search_window_end),
},
})
);
} catch (e) {
setError(e as Error);
} finally {
setLoading(false);
}
}, [getStdcmSearchEnvironment]);
useEffect(() => {
loadStdcmEnvironment();
}, [loadStdcmEnvironment]);
return { loading, error, loadStdcmEnvironment };
}