I started a project with next js and typescript. I have a main component that I call it in the index.js page I use the getStaticProps function in the main component getStaticProps returns a prop object and when I log this prop in my main component I received undefined in my console. I want to know using the getStaticProps in the component is wrong and I have just to use that function in pages or not. I am a newbie in next js and I would be very grateful if anyone could help me.
this is my main component
import React from 'react';
import {IMain} from "../../../../interfaces/components/IMenu/IMain";
const Main:React.FC<IMain> = (props) => {
console.log(props);
return (
<div>
</div>
);
};
export async function getServerSideProps() {
return {
props: {
data: 'gg'
}
};
}
export default Main;
and this is my index.js page
import Text from "./../components/ui/Text/Text";
import Button from "../components/ui/Button/Button";
import Main from "../components/Menu/Desktop/Main/Main";
const Home = () => {
return <Main/>;
};
export default Home;
getStaticProps can only be exported from a page. You can't export it from non-page files.It will not work if you add getStaticProps as a property of the page component.
Bug Solution. You cannot use getServerSideProps in non-page components. getServerSideProps can only be exported from a page. You can't export it from non-page files.
You should use getStaticProps if: The data required to render the page is available at build time ahead of a user's request. The data comes from a headless CMS. The page must be pre-rendered (for SEO) and be very fast — getStaticProps generates HTML and JSON files, both of which can be cached by a CDN for performance.
You can achieve this by just switching the function getStaticProps to getServerSideProps . The entire function will execute on the server and your redirection will happen. e.g.
getStaticProps can only be exported from a page. You can’t export it from non-page files.It will not work if you add getStaticProps as a property of the page component.
https://nextjs.org/docs/basic-features/data-fetching#only-allowed-in-a-page
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With