0

I want to fetch data according to id. I have the id in my URL. So I need to get that id from the URL using useRouter. But when I call useRouter inside getServerSideProps for fetching data on the server side, it gives me this error: Invalid hook call. Hooks can only be called inside of the body of a function component.

Here is my code:

import React from 'react';
import { useRouter } from 'next/router';

const singleProject = (props) => {
return (
    <div>
        <h1>This is project Detail</h1>
    </div>
);
};

export const getServerSideProps = async () => {
  const router = useRouter();
  const id = router.params;
  console.log(id)
  // const data = axios.get(`http://localhost:5000/project/${}`)

  // return {
  //     props: {

  //     }
  // }
  }
  export default singleProject;
Moin khan
  • 1
  • 1
  • export const getServerSideProps = async (ctx) => { console.log(ctx); const router = useRouter(); const id = router.params; console.log(id) // const data = axios.get(`http://localhost:5000/project/${}`) // return { // props: { // } // } } You can get router from that ctx – Dheeraj Sharma Jun 24 '22 at 18:18
  • You can't use the `useRouter` hook inside `getServerSideProps` because React hooks can only be used inside React components (or other hooks). `getServerSideProps` is neither, it's just a special Next.js function that runs on the server. To access a route param inside `getServerSideProps` you can use the `context` object, see [How to access route parameter inside getServerSideProps in Next.js?](https://stackoverflow.com/questions/69058259/how-to-access-route-parameter-inside-getserversideprops-in-next-js). – juliomalves Jun 26 '22 at 21:32

1 Answers1

2

You can only have the router object in the client. In getServerSideProps(), you can use context though.

You can use context.query.id:

export const getServerSideProps = async (context) => {
  const { query } = context;
  const { id } = query;

Source

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39