Skip to content
38 changes: 34 additions & 4 deletions frontend/components/questions/question-view-edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import useSWR from "swr";
import QuestionForm from "@/components/questions/question-form";
import { useAuth } from "@/app/auth/auth-context";
import { useEffect, useState } from "react";
import { updateQuestion } from "@/lib/update-question";
import { useToast } from "@/components/hooks/use-toast";
import LoadingScreen from "@/components/common/loading-screen";

const fetcher = async (url: string): Promise<Question> => {
Expand Down Expand Up @@ -35,8 +37,9 @@ export default function QuestionViewEdit({
questionId: string;
}) {
const auth = useAuth();
const { toast } = useToast();

const { data, isLoading } = useSWR(
const { data, isLoading, mutate } = useSWR(
`http://localhost:8000/questions/${questionId}`,
fetcher
);
Expand All @@ -47,9 +50,36 @@ export default function QuestionViewEdit({
setQuestion(data);
}, [data]);

const handleEdit = (question: Question) => {
// Todo: Implement
question;
const handleEdit = async (question: Question) => {
const response = await updateQuestion(question);
if (!response.ok) {
toast({
title: "Unknown Error",
description: "An unexpected error has occurred",
});
}
switch (response.status) {
case 200:
toast({
title: "Success",
description: "Question updated successfully!",
});
break;
case 404:
toast({
title: "Question not found",
description: "Question with specified ID not found",
});
return;
case 409:
toast({
title: "Duplicated title",
description: "The title you entered is already in use",
});
return;
}

mutate();
};

if (isLoading) {
Expand Down
8 changes: 3 additions & 5 deletions frontend/components/questions/questions-listing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export default function QuestionListing() {
</Button>
</div>
);
}
};

const handleFileSelect = (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
Expand Down Expand Up @@ -213,9 +213,7 @@ export default function QuestionListing() {
</Button>
</label>
</div>
<div>
{createNewQuestion()}
</div>
<div>{createNewQuestion()}</div>
</div>
)}
<QuestionTable
Expand All @@ -232,4 +230,4 @@ export default function QuestionListing() {
/>
</div>
);
}
}
15 changes: 15 additions & 0 deletions frontend/lib/update-question.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Question } from "./schemas/question-schema";

export const updateQuestion = async (question: Question) => {
const response = await fetch(
`http://localhost:8000/questions/${question.id}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(question),
}
);
return response;
};