'use client'
import axios, { AxiosResponse } from 'axios'
import useSWR from 'swr'
import { useState } from 'react'
type TestResponse = {
userId: string
id: string
title: string
body: string
}
type TestRequest = {
url: string
postId: string
}
const fetcher = async (request: TestRequest) =>
await axios
.post(request.url, { postId: request.postId })
.then((res: AxiosResponse<TestResponse>) => res.data)
export default function RouteHandlers() {
const [postId, setPostId] = useState('1')
const { data, error, isLoading } = useSWR<TestResponse, Error>(
['/api/routeHandlers', postId],
([url, postId]: [url: string, postId: string]) => fetcher({ url, postId }),
)
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
const targetElement = e.currentTarget?.postId as HTMLInputElement
if (targetElement) {
setPostId(targetElement.value)
}
}
if (error) {
return <div>Failed to load</div>
}
if (isLoading) {
return <div>Loading...</div>
}
return (
<div>
<div>
<form onSubmit={handleSubmit}>
<input name='postId' type='number' required placeholder='enter postId' />
<button>search</button>
</form>
</div>
<div>
{data && Object.keys(data).length !== 0 ? (
<div>
<div key={data.id}>
<h3>{data.title}</h3>
<p title={data.body}>{data.body}</p>
</div>
</div>
) : (
<h2>Not found</h2>
)}
</div>
</div>
)
}