bot-image-moderation-fe/src/components/ImageModerator/ImageModerator.tsx

122 lines
2.8 KiB
TypeScript

import Button from "../Button/Button";
import { useEffect, useState } from "react";
// Let the user input the middleware URL, API url and app + secret
const MWURL = "http://localhost:8081";
const APIURL = "http://localhost:8080";
const app = "tester";
const secret = "test";
export default function ImageModerator() {
const acceptLabel = "Accept";
const discardLabel = "Discard";
const endpoint = `${MWURL}/image`;
const [isLoading, setIsLoading] = useState(true);
const [imageSrc, setImageSrc] = useState("");
const [imageAlt, setImageAlt] = useState("No image");
const [token, setToken] = useState("");
useEffect(() => {
fetch(`${APIURL}/login`, {
method: "POST",
body: JSON.stringify({ app, secret }),
headers: { "Content-type": "application/json" },
})
.then((response) => {
return response.json();
})
.then((body) => {
setToken(body.token);
});
}, []);
console.log(token);
function acceptAction() {
fetch(`${APIURL}/images`, {
method: "POST",
body: `{ "url": "${imageSrc}", "status": "available", "tags": [] }`,
headers: {
"Content-type": "application/json",
Authorization: `Bearer ${token}`,
},
});
setIsLoading(true);
}
function discardAction() {
fetch(`${APIURL}/images`, {
method: "POST",
body: `{ "url": "${imageSrc}", "status": "unavailable", "tags": [] }`,
headers: {
"Content-type": "application/json",
Authorization: `Bearer ${token}`,
},
});
setIsLoading(true);
}
const getNewImage = () => {
setImageSrc("");
fetch(endpoint, {
method: "GET",
})
.then((response) => {
if (!response.ok) throw new Error("Response was not ok");
return response.json();
})
.then((data) => {
const imageUrl = data.url;
setImageSrc(imageUrl);
})
.catch((error) => {
setImageAlt("Error");
console.error(error);
})
.finally(() => {
setIsLoading(false);
});
};
useEffect(getNewImage, [isLoading]);
return (
<div
style={{
display: "grid",
gridTemplateColumns: "1fr 1fr",
gridTemplateRows: "1fr 50px",
gridTemplateAreas: "'. .' '. .'",
width: "100vw",
height: "100vh",
}}>
{isLoading ? (
<span>Loading...</span>
) : (
<img
src={imageSrc}
alt={imageAlt}
style={{
width: "100%",
height: "100%",
gridColumnStart: 1,
gridColumnEnd: 3,
display: "block",
objectFit: "contain",
}}
/>
)}
<Button
label={acceptLabel}
action={acceptAction}
/>
<Button
label={discardLabel}
action={discardAction}
/>
</div>
);
}