Okay, so here is my problem. I am getting props via getserversideprops, and I have tried multiple fixes but I can not get it to display. Here is the code:
import React, { Component } from 'react';
import rpstyle from '/styles/home/recentPosts.module.css'
export default class RecentPosts extends Component {
constructor() {
super()
this.state = { posts: this.props.posts }
}
static async getServerSideProps() {
const res = await fetch('http://localhost:5000/search/recentposts')
const json = await res.json()
return { posts : json }
}
viewAllButton(){
if(this.props.viewAll != false){
return (
<div className={rpstyle.viewAll}>
<a href='#'>View All Posts</a>
</div>
)
} else {
return null
}
}
render() {
return (
<div className={rpstyle.container}>
<hr />
<h1>Recent Posts</h1>
{console.log(this.props.posts)}
{this.viewAllButton()}
</div>
)
}
}
For some reason I can not find a good guide for class-based components and this method. If someone has any ideas on making this not display undefined
please let me know!
CodePudding user response:
hi you can use the same api for classes as well, if you are using a recent version of next you need to change the return object of getServerSideProps, it needs to have a props key
import React, { Component } from 'react';
export default class RecentPosts extends Component {
constructor(props) {
super(props)
this.state = { posts: props.data }
}
viewAllButton(){
if(this.props.viewAll != false){
return (
<div className={rpstyle.viewAll}>
<a href='#'>View All Posts</a>
</div>
)
} else {
return null
}
}
render() {
return (
<>
<hr />
<h1>Recent Posts</h1>
{console.log(this.state)}
{/* {this.viewAllButton()} */}
</>
)
}
}
export async function getServerSideProps() {
const res = await fetch('https://reqres.in/api/users')
const json = await res.json()
return { props : json }
}
CodePudding user response:
Okay, I took a little bit from your answers as well some more research and found this to work great:
import Recentstuff from '../components/home/recentposts/RecentPosts'
export default function Home({data}) {
return (
<div>
<Recentstuff posts={data} />
</div>
)
}
export const getServerSideProps = async () => {
const res = await fetch('http://localhost:5000/search/recentposts')
const data = await res.json()
return { props : {data} }
}
I hope this helps anyone who had the same issue. You have to call it within the page file, the pass it as a prop. MAKE SURE you properly destructure it, because I had a good little time tracking down why my api calls were showing on my api but not within my client.