I have implemented fetch and set it into object. However, when I want to get its value. It shows undefined, I have no idea about this. Here is the code.
import {useEffect,useState} from 'react';
import { useRouter, Router } from 'next/router';
import Layout from '../../components/MyLayout';
import Settings from '../../components/Settings';
const Post = (props) => {
const [object, setObject] = useState({});
const router = useRouter();
useEffect(
() => {
const data = router.query;
const FormData = new URLSearchParams();
FormData.append('slug',data.id);
fetch(Settings.api+'viewPost',{
method: 'POST',
body: FormData
})
.then(res=>res.json())
.catch(function(e){
console.log(e)}
)
.then(obj=>{
setObject(obj.data[0])
})
}
, [router.query]
)
return (
<Layout>
<h1>{object.title}</h1> --> I would like to display here
</Layout>
);
}
export default Post;
Anyway here is the json I would like to implement
{
"page": 1,
"total": 0,
"data": [
{
"postId": 4,
"boardId": "",
"username": "[email protected]",
"title": "How To Make Money",
"slug": "how-to-make-money",
"answer": 0,
"checked": 0,
"status": "",
"waktu": "2019-10-16 04:45:30"
}
]
}
Here is the error
TypeError: Cannot read property 'title' of undefined
I really appreciate any answer. Thank you.