/
useSuggestToggle.ts
59 lines (54 loc) · 1.98 KB
/
useSuggestToggle.ts
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
52
53
54
55
56
57
58
59
import { useCallback, useState } from 'react';
import useToast from 'hooks/useToast';
import { formatUnknownError } from 'utils/formatUnknownError';
import { useSuggestChangeApi } from './api/actions/useSuggestChangeApi/useSuggestChangeApi';
export const useSuggestToggle = (project: string) => {
const { setToastData, setToastApiError } = useToast();
const { addSuggestion } = useSuggestChangeApi(project);
const [suggestChangesDialogDetails, setSuggestChangesDialogDetails] =
useState<{
enabled?: boolean;
featureName?: string;
environment?: string;
isOpen: boolean;
}>({ isOpen: false });
const onSuggestToggle = useCallback(
(featureName: string, environment: string, enabled: boolean) => {
setSuggestChangesDialogDetails({
featureName,
environment,
enabled,
isOpen: true,
});
},
[]
);
const onSuggestToggleClose = useCallback(() => {
setSuggestChangesDialogDetails({ isOpen: false });
}, []);
const onSuggestToggleConfirm = useCallback(async () => {
try {
await addSuggestion(suggestChangesDialogDetails.environment!, {
feature: suggestChangesDialogDetails.featureName!,
action: 'updateEnabled',
payload: {
enabled: Boolean(suggestChangesDialogDetails.enabled),
},
});
setSuggestChangesDialogDetails({ isOpen: false });
setToastData({
type: 'success',
title: 'Changes added to the draft!',
});
} catch (error) {
setToastApiError(formatUnknownError(error));
setSuggestChangesDialogDetails({ isOpen: false });
}
}, [addSuggestion]);
return {
onSuggestToggle,
onSuggestToggleClose,
onSuggestToggleConfirm,
suggestChangesDialogDetails,
};
};