简体   繁体   中英

Next.js - How to pass id from query to getInitialProps function

I want to build a simple website with articles from db. My problem is that I need these articles to be rendered with server and I can do it with getInitialProps function from Next.js documentation: https://nextjs.org/docs/api-reference/data-fetching/getInitialProps#getinitialprops-for-older-versions-of-nextjs

For now It's working properly but I want to implement getting article by its ID and my link should be like that:

http://localhost:3000/articles/<some_id>

I have done that but now I want to read that ID and pass it to getInitialProps function to call my API for only one specific article. My problem is that I don't know how to pass down router props to get that ID from query and call API.

import { withRouter } from "next/router";
import fetch from "isomorphic-unfetch";

const Article = ({ router }) => {
  console.log(router);
  return (
    <div>
      <h1>Hello World</h1>
    </div>
  );
};

Article.getInitialProps = async props => {
  console.log(props);
  const res = await fetch(
    `https://admin.jozefrzadkosz-portfolio.pl/articles/${router.query.id}`
  );
  const articles = await res.json();
  return { articles };
};

export default withRouter(Article);

getInitialProps get as an argument context object, which has query on it.

You should get your value in there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM