1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-12-28 00:06:53 +01:00
unleash.unleash/frontend/src/hooks/useChangeRequestToggle.ts

86 lines
2.9 KiB
TypeScript
Raw Normal View History

import { useCallback, useState } from 'react';
import useToast from 'hooks/useToast';
import { formatUnknownError } from 'utils/formatUnknownError';
import { useChangeRequestApi } from './api/actions/useChangeRequestApi/useChangeRequestApi';
import { usePendingChangeRequests } from './api/getters/usePendingChangeRequests/usePendingChangeRequests';
export const useChangeRequestToggle = (project: string) => {
const { setToastData, setToastApiError } = useToast();
2022-11-30 12:04:29 +01:00
const { addChange } = useChangeRequestApi();
const { refetch: refetchChangeRequests } =
usePendingChangeRequests(project);
const [pending, setPending] = useState(false);
const [changeRequestDialogDetails, setChangeRequestDialogDetails] =
useState<{
enabled?: boolean;
shouldActivateDisabledStrategies?: boolean;
featureName?: string;
environment?: string;
isOpen: boolean;
}>({ isOpen: false });
const onChangeRequestToggle = useCallback(
(
featureName: string,
environment: string,
enabled: boolean,
shouldActivateDisabledStrategies: boolean,
) => {
setChangeRequestDialogDetails({
featureName,
environment,
enabled,
shouldActivateDisabledStrategies,
isOpen: true,
});
},
[],
);
const onChangeRequestToggleClose = useCallback(() => {
setChangeRequestDialogDetails((prev) => ({ ...prev, isOpen: false }));
}, []);
const onChangeRequestToggleConfirm = useCallback(async () => {
try {
setPending(true);
2022-11-30 12:04:29 +01:00
await addChange(project, changeRequestDialogDetails.environment!, {
feature: changeRequestDialogDetails.featureName!,
action: 'updateEnabled',
payload: {
enabled: Boolean(changeRequestDialogDetails.enabled),
shouldActivateDisabledStrategies: Boolean(
changeRequestDialogDetails.shouldActivateDisabledStrategies,
),
2022-11-30 12:04:29 +01:00
},
});
refetchChangeRequests();
setChangeRequestDialogDetails((prev) => ({
...prev,
isOpen: false,
}));
setToastData({
type: 'success',
title: 'Changes added to the draft!',
});
} catch (error) {
setToastApiError(formatUnknownError(error));
setChangeRequestDialogDetails((prev) => ({
...prev,
isOpen: false,
}));
} finally {
setPending(false);
}
2022-11-30 12:04:29 +01:00
}, [addChange]);
return {
pending,
onChangeRequestToggle,
onChangeRequestToggleClose,
onChangeRequestToggleConfirm,
changeRequestDialogDetails,
};
};