67 lines
No EOL
1.9 KiB
TypeScript
67 lines
No EOL
1.9 KiB
TypeScript
import { useEffect, useState } from "preact/hooks"
|
|
import { api, BROWSER_ID, type Reaction } from "../lib/api"
|
|
import { v7 as uuidv7 } from 'uuid';
|
|
|
|
export default function Reaction({ slug }: { slug: string }) {
|
|
const [reaction, setReaction] = useState<Reaction>({ slug: slug, browser_id: "" })
|
|
const [reactionCount, setReactionCount] = useState(0)
|
|
const [haveReacted, setHaveReacted] = useState(false)
|
|
|
|
useEffect(() => {
|
|
let browserId = localStorage.getItem(BROWSER_ID)
|
|
|
|
if (!browserId) {
|
|
browserId = uuidv7()
|
|
localStorage.setItem(BROWSER_ID, browserId)
|
|
}
|
|
|
|
api.haveIReacted({ ...reaction, browser_id: browserId }).then((response: boolean) => {
|
|
setHaveReacted(response)
|
|
})
|
|
|
|
api.reactionCount(slug).then((count) => {
|
|
setReactionCount(count)
|
|
})
|
|
|
|
setReaction(prev => ({ ...prev, browser_id: browserId }))
|
|
}, [])
|
|
|
|
const handleReaction = () => {
|
|
let hasError = false
|
|
if (!haveReacted) {
|
|
try { api.createReaction(reaction) }
|
|
catch (e) { hasError = true }
|
|
finally {
|
|
if (!hasError) {
|
|
setHaveReacted(true)
|
|
setReactionCount(prev => prev + 1)
|
|
}
|
|
}
|
|
} else {
|
|
try { api.deleteReaction(reaction) }
|
|
catch (e) { hasError = true }
|
|
finally {
|
|
if (!hasError) {
|
|
setHaveReacted(false)
|
|
setReactionCount(prev => prev - 1)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
return (
|
|
<button onClick={handleReaction}
|
|
|
|
style="
|
|
font-size: 1rem;
|
|
width: 100%;
|
|
padding:8px;
|
|
font-family:Arial, Helvetica, sans-serif;
|
|
">
|
|
|
|
|
|
{haveReacted ? "♥ Yeah!" : "Hattest du Spaß beim Lesen?"} {reactionCount}
|
|
</button>
|
|
)
|
|
}
|