import { useEffect, useState } from "react"; import { currentPage, Pages } from "./VerticalMenu" import { RecoilRoot, useRecoilState } from 'recoil' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faPaperPlane } from '@fortawesome/free-solid-svg-icons' import { formatDistance } from 'date-fns' import { ja } from 'date-fns/locale/ja' export default function Chat() { const [page, _] = useRecoilState(currentPage); const [name, setName] = useState(""); const [body, setBody] = useState(""); const [messages, setMessages] = useState(); const [alert, setAlert] = useState(""); interface Message { name: string body: string createdAt: string } useEffect(() => { if (page === Pages.Chat) { updateChat(); } }, [page]); async function submit() { await fetch( "https://bbs.yude.workers.dev/api/message", { method: "POST", headers: { "Content-Type": "application/json", }, mode: 'cors', body: JSON.stringify({ name: name, body: body, }) } ) .then( (res) => res.text() ) .then ( async (text) => { if (text.includes("Success")) { await showAlert("送信しました。"); } } ) await new Promise(s => setTimeout(s, 800)); updateChat(); } const updateChat = () => { fetch( "https://bbs.yude.workers.dev/api/messages", ) .then((res) => res.json()) .then((data) => setMessages(data)); } const updateName = (e: any) => { setName(e.target.value); } const updateBody = (e: any) => { setBody(e.target.value); } async function showAlert(alert: string) { setAlert(alert); await new Promise(s => setTimeout(s, 1500)); setAlert(""); } return (
{alert}
{ messages && messages.map((message, index) => { return (

{message.name} さん,{" "} { formatDistance(Date.parse(message.createdAt), new Date(), { addSuffix: true, locale: ja }) }

{message.body}

) }) }
) }