79 lines
2.1 KiB
TypeScript
79 lines
2.1 KiB
TypeScript
import { useEffect, useState } from 'react'
|
|
import { useForm, type SubmitHandler } from 'react-hook-form'
|
|
import { getCookie } from 'typescript-cookie'
|
|
import { DeletePost } from './api'
|
|
|
|
type Inputs = {
|
|
id: number,
|
|
hash: string
|
|
}
|
|
|
|
export const Delete = () => {
|
|
const {
|
|
register,
|
|
handleSubmit,
|
|
watch,
|
|
setValue,
|
|
formState: { errors },
|
|
} = useForm<Inputs>()
|
|
const onSubmit: SubmitHandler<Inputs> = (data) => {
|
|
console.log(data)
|
|
DeletePost(data.id, data.hash).then(
|
|
e => {
|
|
if (e) {
|
|
alert("成功刪除")
|
|
}
|
|
}
|
|
)
|
|
}
|
|
let [saved, setSaved] = useState<{ id: number, hash: string }[]>([])
|
|
useEffect(() => {
|
|
let cred = getCookie("post_cred")
|
|
if (cred) {
|
|
let parsed: { id: number, hash: string }[] = JSON.parse(cred)
|
|
console.log(parsed)
|
|
setSaved(parsed)
|
|
}
|
|
}, [])
|
|
let current_id = watch("id")
|
|
let mem_hash = saved.find(e => e.id == current_id)
|
|
useEffect(() => {
|
|
if (mem_hash) {
|
|
setValue("hash", mem_hash.hash)
|
|
}
|
|
}, [mem_hash])
|
|
|
|
|
|
return (
|
|
<>
|
|
<form
|
|
onSubmit={handleSubmit(onSubmit)}
|
|
className=
|
|
'flex flex-col m-auto w-10/12 h-[80dvh] px-10 gap-3 pb-3 md:w-[50dvw]'
|
|
>
|
|
{/* register your input into the hook by invoking the "register" function */}
|
|
<h1 className="text-3xl my-3">刪除匿名</h1>
|
|
<label htmlFor='id' className='text-left'>
|
|
ID:
|
|
</label>
|
|
<input id="id" type="search" {...register("id", { required: true })} className='border-b-4 border-zinc-500 w-full text-end outline-none focus:border-zinc-200' list="saved_id" />
|
|
<datalist id="saved_id">
|
|
{saved.map((e, it) => <option value={e.id} key={it}></option>)}
|
|
</datalist>
|
|
|
|
<label htmlFor='hash'>
|
|
Hash:
|
|
</label>
|
|
<input id="hash" type="text" {...register("hash", { required: true })} className='border-b-4 border-zinc-500 w-full text-end outline-none focus:border-zinc-200' />
|
|
|
|
{/* errors will return when field validation fails */}
|
|
{errors.id && <span>This field is required</span>}
|
|
{errors.hash && <span>This field is required</span>}
|
|
|
|
<button type="submit" className="ring-3 w-full mx-auto rounded-md ">
|
|
刪除
|
|
</button>
|
|
</form>
|
|
</>
|
|
)
|
|
}
|