feat: Implement client-side routing for person list and details, including adding opinions.
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { Person, AddOpinionRequest } from "../items";
|
||||
|
||||
interface Props {
|
||||
token: string;
|
||||
}
|
||||
|
||||
export const PersonDetails = ({ token }: Props) => {
|
||||
const { name } = useParams<{ name: string }>();
|
||||
const [person, setPerson] = useState<Person | null>(null);
|
||||
const [gameTitle, setGameTitle] = useState("");
|
||||
const [wouldPlay, setWouldPlay] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (name) {
|
||||
fetch(`/api/${name}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
.then((res) => res.arrayBuffer())
|
||||
.then((buffer) => {
|
||||
try {
|
||||
setPerson(Person.decode(new Uint8Array(buffer)));
|
||||
} catch (e) {
|
||||
console.error("Failed to decode person:", e);
|
||||
}
|
||||
})
|
||||
.catch(console.error);
|
||||
}
|
||||
}, [name, token]);
|
||||
|
||||
const handleAddOpinion = async () => {
|
||||
if (!person) return;
|
||||
|
||||
const req = AddOpinionRequest.create({
|
||||
gameTitle,
|
||||
wouldPlay,
|
||||
});
|
||||
|
||||
const buffer = AddOpinionRequest.encode(req).finish();
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/opinion", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/octet-stream",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: buffer,
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
const resBuffer = await res.arrayBuffer();
|
||||
setPerson(Person.decode(new Uint8Array(resBuffer)));
|
||||
setGameTitle("");
|
||||
setWouldPlay(false);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
};
|
||||
|
||||
if (!person) return <div>Loading...</div>;
|
||||
|
||||
return (
|
||||
<div className="card">
|
||||
<h2>{person.name}</h2>
|
||||
<ul>
|
||||
{person.opinion.map((op, i) => (
|
||||
<li key={i}>
|
||||
{op.title} - {op.wouldPlay ? "Would Play" : "Would Not Play"}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<div
|
||||
style={{
|
||||
marginTop: "2rem",
|
||||
borderTop: "1px solid #ccc",
|
||||
paddingTop: "1rem",
|
||||
}}
|
||||
>
|
||||
<h3>Add Opinion</h3>
|
||||
<div style={{ display: "flex", gap: "1rem", alignItems: "center" }}>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Game Title"
|
||||
value={gameTitle}
|
||||
onChange={(e) => setGameTitle(e.target.value)}
|
||||
/>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={wouldPlay}
|
||||
onChange={(e) => setWouldPlay(e.target.checked)}
|
||||
/>
|
||||
Would Play
|
||||
</label>
|
||||
<button onClick={handleAddOpinion}>Add</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user