2022-10-26 22:28:55 +02:00
|
|
|
import type { Comment } from "../interfaces";
|
2022-11-09 19:51:22 +01:00
|
|
|
import React, { useState } from "react";
|
2021-06-11 04:04:33 +02:00
|
|
|
import useSWR from "swr";
|
|
|
|
import { useAuth0 } from "@auth0/auth0-react";
|
|
|
|
|
2024-02-14 16:03:40 +01:00
|
|
|
const fetcher = (url) =>
|
|
|
|
fetch(url).then((res) => {
|
|
|
|
if (res.ok) {
|
|
|
|
return res.json();
|
|
|
|
}
|
|
|
|
|
|
|
|
throw new Error(`${res.status} ${res.statusText} while fetching: ${url}`);
|
|
|
|
});
|
2022-10-26 22:28:55 +02:00
|
|
|
|
2021-06-11 04:04:33 +02:00
|
|
|
export default function useComments() {
|
|
|
|
const { getAccessTokenSilently } = useAuth0();
|
|
|
|
const [text, setText] = useState("");
|
|
|
|
|
2022-10-26 22:28:55 +02:00
|
|
|
const { data: comments, mutate } = useSWR<Comment[]>(
|
|
|
|
"/api/comment",
|
|
|
|
fetcher,
|
|
|
|
{ fallbackData: [] },
|
2021-06-11 04:04:33 +02:00
|
|
|
);
|
|
|
|
|
2022-10-26 22:28:55 +02:00
|
|
|
const onSubmit = async (e: React.FormEvent) => {
|
2021-06-11 04:04:33 +02:00
|
|
|
e.preventDefault();
|
|
|
|
const token = await getAccessTokenSilently();
|
|
|
|
|
|
|
|
try {
|
|
|
|
await fetch("/api/comment", {
|
|
|
|
method: "POST",
|
2022-11-09 19:51:22 +01:00
|
|
|
body: JSON.stringify({ text }),
|
2021-06-11 04:04:33 +02:00
|
|
|
headers: {
|
|
|
|
Authorization: token,
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
},
|
|
|
|
});
|
|
|
|
setText("");
|
|
|
|
await mutate();
|
|
|
|
} catch (err) {
|
|
|
|
console.log(err);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2022-10-26 22:28:55 +02:00
|
|
|
const onDelete = async (comment: Comment) => {
|
2021-06-11 04:04:33 +02:00
|
|
|
const token = await getAccessTokenSilently();
|
|
|
|
|
|
|
|
try {
|
|
|
|
await fetch("/api/comment", {
|
|
|
|
method: "DELETE",
|
2022-11-09 19:51:22 +01:00
|
|
|
body: JSON.stringify({ comment }),
|
2021-06-11 04:04:33 +02:00
|
|
|
headers: {
|
|
|
|
Authorization: token,
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
},
|
|
|
|
});
|
|
|
|
await mutate();
|
|
|
|
} catch (err) {
|
|
|
|
console.log(err);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
return { text, setText, comments, onSubmit, onDelete };
|
|
|
|
}
|