I am working in Reactjs(nextjs),And i am tyring to use "hooks" in functional components Right now i am trying to fetch data via api but i am getting following error
TypeError: Trending is undefined
Here is my code,Where i am wrong ?
import Axios from "axios";
import { useRouter } from "next/router";
import Link from "next/link";
const Trending = ({ Trending }) => {
const router = useRouter();
console.log({ Trending });
if (router.isFallback) {
return <div>Loading...</div>;
}
return (
<>
<section>
<div className="container Blog_page_sidebar">
<div className="blog_details">
<div className="blog_image">{Trending.title}</div>
<div className="blog_heading"></div>
<div className="blog_detail"></div>
</div>
</div>
</section>
</>
);
};
export default Trending;
export const getStaticProps = async () => {
const { data } = await Axios.get(
`https://myurl/blogs`
);
const Trending = data;
return {
props: {
Trending,
},
};
};
CodePudding user response:
If you want call API in useEffect
useEffect(() => {
const getData = async() => {
try {
const data = await axios.get(`https://myurl/blogs`);
console.log('data is = ' , data);
setData(data)
}catch(err) {
console.log(err);
}
}
//call the inner function inside useEffect
getData();
)} ,[])
CodePudding user response:
import Axios from "axios";
import { useRouter } from "next/router";
import Link from "next/link";
import React, { useState } from 'react';
const Trending = ({ Trending }) => {
const router = useRouter();
console.log({ Trending });
if (router.isFallback) {
return <div>Loading...</div>;
}
return (
<>
<section>
<div className="container Blog_page_sidebar">
<div className="blog_details">
<div className="blog_image">{Trending.title}</div>
<div className="blog_heading"></div>
<div className="blog_detail"></div>
</div>
</div>
</section>
</>
);
};
export default Trending;
export const getStaticProps = () => {
const [data,setData] = useState([])
const getData = async( ) => {
try{
const response = await Axios.get(`https://myurl/blogs`);
setData(response.data)
}catch(err){
console.log(err)
}
}
useEffect(() => {
getData()
},[])
const Trending = data;
return {
props: {
Trending,
},
};
};