Reputation: 55
I am trying to get the id from the route as http//localhost:3000/portfolios/helloworld so id is helloworld. But i get an error that says TypeError: Cannot destructure property 'id' of 'query' as it is undefined.
const PortfolioDetail = ({ query }) => {
const { id } = query;
return <h1>I am Details Page with ID: {id}</h1>;
};
PortfolioDetail.getInitialProps = ({ query }) => {
return { query };
};
export default PortfolioDetail;
I tried the same thing with class component but the error was same.
// class PortfolioDetail extends React.Component {
// static getInitialProps({ query }) {
// return { query };
// }
// render() {
// const id = this.props.query.id;
// return <h1>I am Detail Page with id : {id} </h1>;
// }
// }
// export default PortfolioDetail;
this is my project structure you can see below image
It only works and i can get my id using useRouter i showed below.
import { useRouter } from 'next/router';
import React from 'react';
const PortfolioDetail = () => {
const router = useRouter();
const id = router.query.id
return <h1>I am Details Page with ID: {id}</h1>;
};
PortfolioDetail.getInitialProps = ({ query }) => {
return { query };
};
export default PortfolioDetail;
I am stuck at this point and i really wanna know why it won't work.
Upvotes: 0
Views: 1130
Reputation: 18506
I've got it, you have an error in your _app
:
import '../styles/index.scss';
import 'bootstrap/dist/css/bootstrap.min.css';
// Don't need to spread pageProps here
const MyApp = ({ Component, ...pageProps }) => {
return <Component {...pageProps} />;
};
export default MyApp;
It should be:
const MyApp = ({ Component, pageProps }) => {
return <Component {...pageProps} />;
};
Upvotes: 1
Reputation: 182
Why dont use it like the code shown below
export default function FirstPost({ id }) {
console.log("-->", id);
return (
<>
{id}sdlfdfdlkj
</>
);
}
FirstPost.getInitialProps = ({ query }) => {
return { id: query?.id };
};
Upvotes: 0