JanetFrontEnd/src/ChatPage.js

93 lines
2.7 KiB
JavaScript

import React, { useState, useEffect, useRef } from "react";
import { useSearchParams, useParams } from "react-router-dom";
import "./style.css";
import ChatBox from "./ChatBox.js";
import FeedbackForm from "./FeedbackForm.js";
const ChatPage = () => {
const [needForm, setNeedForm] = useState(false);
//const { token } = useParams();
const backendUrl = '/api';
const [searchParams, setSearchParams] = useSearchParams();
const token = searchParams.get("gcube-token") || '';
const [messages, setMessages] = useState([]);
const tick = useRef()
const [timer, setTimer] = useState(0);
const [stat, setStat] = useState("start");
const [err, setErr] = useState("");
const version = process.env.REACT_APP_VERSION_INFO;
if (!version) {
console.info("No version information present at build time.");
}else{console.info('version: ${version}');}
useEffect(() => {
if (stat === "waiting"){
let x = "set"
fetch(backendUrl + '/dm', {
method: 'POST',
body: JSON.stringify({stat: x, token: token }),
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
}).then(r => r.json()).then(r => {
setStat(r.stat);
setErr(r.err);
}).catch((error) => {
console.error('Error:', error);
});
}
if (stat==="start"){
tick.current = setInterval(() => {
setTimer((timer) => timer + 1);
}, 1000);
if(timer%30 == 0){
fetch(backendUrl + '/dm', {
method: 'POST',
body: JSON.stringify({ stat: stat, token: token }),
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
}).then(r => r.json()).then(r => {
setStat(r.stat);
setErr(r.err);
}).catch((error) => {
console.error('Error:', error);
});
setTimer((timer) => 0);
clearInterval(tick.current);
}
}
return () => clearInterval(tick.current);
}, [stat, timer]);
function updateNeedForm(value) {
setNeedForm(value);
}
function updateMessages(msg) {
setMessages((prevMessages) => [msg, ...prevMessages]);
}
return (
<div>
{stat==="waiting" && <p>Loading resources + {token} ...</p>}
{stat==="start" && <p>Connecting to Server + {token} ...</p>}
{stat==="rejected" && <p>Unauthorized Use + {token} ...</p>}
{stat==="init_dm_error" && <p> {err} + {token} </p>}
{stat==="done" && <ChatBox props={{ updateNeedForm, messages, updateMessages, token}} /> }
{stat==="done" && needForm && <FeedbackForm props={{ updateNeedForm, messages }} /> }
</div>
);
};
export default ChatPage;