I am making a get request to jasonplaceholder server to fetch data but when I make the request for some time it shows undefined and then all the data comes, how can I stop this undefined and stop the code processing until the data is fully fetched from the server
import React,{useState,useEffect} from 'react'
import {useRouter} from 'next/router'
import axios from 'axios'
export default function Portfolio(){
const router = useRouter();
const [post,setPost] = useState({})
console.log("323")
console.log(router.query.id)
useEffect(() => {
axios.get(`https://jsonplaceholder.typicode.com/posts/${router.query.id}`)
.then(res => {
setPost(res.data)
})
.catch(err => {
console.log(err)
})
},[router.query.id])
return (
<React.Fragment>
<h1>{`userId : ${post.userId}`}</h1>
<h1>{`id : ${post.id}`}</h1>
<h1>{`title : ${post.title}`}</h1>
</React.Fragment>
)
}
const response = await axios('endpoint');
setPost(response);
You can add a condition while rendering the code.
Check the below code:
<React.Fragment>
<h1>{`userId : ${post && post.userId}`}</h1>
<h1>{`id : ${post && post.id}`}</h1>
<h1>{`title : ${post && post.title}`}</h1>
</React.Fragment>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.