I am making a Server Side Rendering application using Next Js (React SSR).
Index.js (Simply calling another component Layout in index)
import Layout from "./layout";
import React from "react";
class Home extends React.Component {
render() {
return (
<div>
<Layout />
</div>
);
}
}
export default Home;
Layout.js
import React from "react";
import Product from "./product";
class Layout extends React.Component {
static async getInitialProps() {
const res = await fetch("https://api.github.com/repos/developit/preact");
console.log(res);
const json = await res.json();
return { stars: json.stargazers_count };
}
componentDidMount() {
if (localStorage.getItem("userLoggedIn")) {
//Get products details for logged in user api
//For now let us consider the same api
// const res = fetch("https://api.github.com/repos/developit/preact");
// const json = res.json(); // better use it inside try .. catch
// return { stars: json.stargazers_count };
} else {
// Get product details for guest user api
//For now let us consider the same api
// const res = fetch("https://api.github.com/repos/developit/preact");
// const json = res.json();
// return { stars: json.stargazers_count };
}
}
render() {
return (
<div>
This is layout page
<Product stars={this.props.stars} />
</div>
);
}
}
export default Layout;
Complete simple application example is here: https://codesandbox.io/s/nextjs-getinitialprops-748d5
My problem here is, I am trying to pass props to product page from layout page and props are received from getInitialProps (SSR).. But you could see in the example provided, the props didn't works and it still gives undefined for this.props.stars .
If I move this code into componentDidMount and using setState and passing state as props would work but that will not display the data fetched from api in view page source.
Note: Please don't move this logic into index.js file where it works but in my real application It is dynamic routing page and I will fetch api as per the query param fetched on that page.
If you get into this link https://748d5.sse.codesandbox.io/ and click ctrl + u then you would see the source where I am also need the dynamic content fetched from api.
To achieve this dynamic content(stars count here in this example) display in view source only I am doing all these which is meant for SEO purpose.