import Head from 'next/head'
import { useState } from 'react'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
const Home = (props) => {
const [blogs, setblogs] = useState(props.data);
return <div className={styles.container}>
<Head>
<title>BlogsWap</title>
<meta name="description" content="New App" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1 className={styles.title}>
Welcome to <a href="https://nextjs.org">BlogsWap!</a>
</h1>
<p className={styles.description}>
An all time blog for coders!
</p>
{blogs.map((blogitem) => {
return <div className={styles.grid}>
<a href="https://nextjs.org/docs" className={styles.card}>
<h2>{blogitem.title} →</h2>
<p>{blogitem.content}</p>
</a>
</div>
})}
</main>
<footer className={styles.footer}>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
© BlogsWap
<span className={styles.logo}>
</span>
</a>
</footer>
</div>
}
export async function getServerSideProps(context) {
let totalBlogs = await fetch('http://localhost:3000/api/blogs');
// console.log(totalBlogs)
let data = await totalBlogs.json();
return {
props: { data }, // will be passed to the page component as props
}
}
export default Home
I am getting error like:
TypeError: blogs.map is not a function
What should I do? I have no idea why it appeared because, recently I have used similar method but it all was fine now it throwing such error! Please help me in to get the error out!
Here is the photo of the error :(
The error you are getting means that the blogs object is undefined and thus, blogs.map is also undefined, raising an error when being called.
Try using optional chaining:
{blogs?.map((blogitem) => {
...
Change the getServerSideProps like this, return something meaningful which actually represents your data, not a keyword like data, it's confusing.
By returning { props: { blogData } }, the component will receive blogData as a prop.
let blogData = await totalBlogs.json();
return {
props: { blogData }, // will be passed to the page component as props
}
Then you need to change the input of component where you are passing props, it's now blogData. Notice the change here, destructuring is being used here.
const Home = ({ blogData }) =>
const [blogs, setblogs] = useState(blogData);
Finally in the jsx also do null check to safely access object
{blogs && ....
<map goes here>
}
Or
{blogs ?
<map goes here>
:
else show a loader here
Also I hope blogData is an array type, if not convert it to array using
Array.from(blogData)
because .map only works on array.
The way you are accessing blogs, you need to pass blogs as a key:
let blogs = await totalBlogs.json();
return {
props: { data : { blogs } }, // will be passed to the page component as props
}
Or you can do this:
const [blogs, setblogs] = useState(props);