kandimat/redaktions-app/src/components/DialogDeleteQuestion.tsx
2021-01-09 12:49:28 +01:00

83 lines
2.3 KiB
TypeScript

import React from "react";
import {
makeVar,
Reference,
useMutation,
useReactiveVar,
} from "@apollo/client";
import DialogSimple from "./DialogSimple";
import {
DELETE_QUESTION,
DeleteQuestionResponse,
DeleteQuestionVariables,
} from "../backend/mutations/question";
import { useSnackbar } from "notistack";
export const dialogDeleteQuestionId = makeVar<string>("");
export const dialogDeleteQuestionTitle = makeVar<string>("");
export const dialogDeleteQuestionOpen = makeVar<boolean>(false);
export default function DialogDeleteQuestion() {
const { enqueueSnackbar } = useSnackbar();
const [deleteQuestion, { loading }] = useMutation<
DeleteQuestionResponse,
DeleteQuestionVariables
>(DELETE_QUESTION, {
onError: (e) =>
enqueueSnackbar(`Ein Fehler ist aufgetreten: ${e.message}`, {
variant: "error",
}),
onCompleted: (response) => {
if (response.deleteQuestion) {
enqueueSnackbar("Frage erfolgreich gelöscht.", { variant: "success" });
dialogDeleteQuestionOpen(false);
} else {
enqueueSnackbar("Ein Fehler ist aufgetreten, versuche es erneut.", {
variant: "error",
});
}
},
update: (cache, { data }) => {
const idToRemove = data?.deleteQuestion?.question.id;
cache.modify({
fields: {
allQuestions(
existingQuestionsRef: { nodes: Array<Reference> } = { nodes: [] },
{ readField }
) {
return {
nodes: existingQuestionsRef.nodes.filter(
(questionRef) => readField("id", questionRef) !== idToRemove
),
};
},
},
});
},
});
const open = useReactiveVar(dialogDeleteQuestionOpen);
const title = useReactiveVar(dialogDeleteQuestionTitle);
const id = useReactiveVar(dialogDeleteQuestionId);
const handleConfirmButtonClick = () => {
deleteQuestion({
variables: {
id,
},
});
};
return (
<DialogSimple
open={open}
title={"Frage löschen?"}
description={`Möchtest du die Frage "${title}" wirklich löschen?`}
confirmButtonText={"Löschen"}
onConfirmButtonClick={handleConfirmButtonClick}
onClose={() => dialogDeleteQuestionOpen(false)}
loading={loading}
/>
);
}