3

I am trying to get data from the API by using POST Method, However, I am struggling to set the data into post

import { useRouter } from 'next/router';
import Layout from '../../components/MyLayout';
import Settings from '../../components/Settings';

const Post = props =>{
    //works if I use here
    const router = useRouter();
  return (
    <Layout>
      <h1>{router.query.id}</h1>
      <p>This is the blog post content.</p>
    </Layout>
  );
}

export default Post;

Post.getInitialProps = async function(){
    //trying to get data ($_GET)
    const router = useRouter();
    const data = router.query;
    //
    const FormData = new URLSearchParams();
    const res = await fetch(Settings.api+'viewPost',{
        method: 'POST',
        headers:{
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: FormData,
    });
    const obj = await res.json();
    return(
        obj
    );
}

I receive this following error

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See *** for tips about how to debug and fix this problem.

I just learn about this, sorry for the dumb question. I really appreciate any answer. Thank you.

Raden Bagus
  • 314
  • 4
  • 14

1 Answers1

7

I did the exact same thing (try to use useRouter in getinitialProps) as you and get the same error just now, then I search around and found how to get query string parameter in next , so to answer your question , you don't need useRouter in this case but instead use getInitialProps (props) and find the query params to get your data or Id or whatever. Hope that helps.

Post.getInitialProps = async function({ query }){
   const { data } = query;
     ...................
}
nymhays
  • 468
  • 3
  • 12
  • how can I handle to situation I have a custom hook store global state and I want to get it in getInitialProps? – huykon225 Mar 17 '23 at 06:33