An error showing
Error: Error serializing
.myBlogsreturned fromgetServerSidePropsin "/blog".```
while I am trying to console data! While I was fetching data through useEffect() everything was going well, but now fetching data with getServerSideProps it throws error mentioned above!
Code:
import React, { useEffect, useState } from 'react'
import styles from '../styles/Blog.module.css'
import Link from 'next/link'
import Navbar from '../components/Navbar'
const blog = (props) => {
console.log(props)
const [blogs, setblogs] = useState([]);
// useEffect(() => {
// }, [])
return <div>
<Navbar />
<main className={styles.main}>
<h2 className={styles.heading}>
Latest Blogs :)
{/* Get started by editing{' '}
<code className={styles.code}>pages/index.js</code> */}
</h2>
<div className={styles.neat}>
{blogs.map((blogitem) => {
return <div className={styles.grid} key={blogitem.slug} >
<Link href={`/blogpost/${blogitem.slug}`} >
<a className={styles.card}>
<h2>{blogitem.title} →</h2>
<p>{blogitem.content.substr(0, 100)}...</p>
</a>
</Link>
</div>
})}
</div>
</main>
</div>
}
export async function getServerSideProps(context) {
let data = await fetch('http://localhost:3000/api/blogs');
let myBlogs = await data.json();
return {
props: {myBlogs}, // will be passed to the page component as myBlogs
}
}
export default blog
As @Bravo suggested, you should await the data.json() call in the getServerSideProps callback.
Also, you should destructure the props object to receive the blogs loaded and display them.
Finally, it is good practice in React to capitalize component names:
const Blog = ({ blogs }) => {
return <div>
<Navbar />
<main className={styles.main}>
<h2 className={styles.heading}>
Latest Blogs :)
{/* Get started by editing{' '}
<code className={styles.code}>pages/index.js</code> */}
</h2>
<div className={styles.neat}>
{blogs.map((blogitem) => {
return <div className={styles.grid} key={blogitem.slug} >
<Link href={`/blogpost/${blogitem.slug}`} >
<a className={styles.card}>
<h2>{blogitem.title} →</h2>
<p>{blogitem.content.substr(0, 100)}...</p>
</a>
</Link>
</div>
})}
</div>
</main>
</div>
}
export async function getServerSideProps(context) {
let data = await fetch('http://localhost:3000/api/blogs');
let myBlogs = await data.json();
return {
props: { blogs: myBlogs },
}
}
export default Blog