File size: 1,524 Bytes
1e92f2d |
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 60 61 62 63 64 65 |
import type { Comment } from "../interfaces";
import React, { useState } from "react";
import useSWR from "swr";
import { useAuth0 } from "@auth0/auth0-react";
const fetcher = (url) =>
fetch(url).then((res) => {
if (res.ok) {
return res.json();
}
throw new Error(`${res.status} ${res.statusText} while fetching: ${url}`);
});
export default function useComments() {
const { getAccessTokenSilently } = useAuth0();
const [text, setText] = useState("");
const { data: comments, mutate } = useSWR<Comment[]>(
"/api/comment",
fetcher,
{ fallbackData: [] },
);
const onSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const token = await getAccessTokenSilently();
try {
await fetch("/api/comment", {
method: "POST",
body: JSON.stringify({ text }),
headers: {
Authorization: token,
"Content-Type": "application/json",
},
});
setText("");
await mutate();
} catch (err) {
console.log(err);
}
};
const onDelete = async (comment: Comment) => {
const token = await getAccessTokenSilently();
try {
await fetch("/api/comment", {
method: "DELETE",
body: JSON.stringify({ comment }),
headers: {
Authorization: token,
"Content-Type": "application/json",
},
});
await mutate();
} catch (err) {
console.log(err);
}
};
return { text, setText, comments, onSubmit, onDelete };
}
|