I get this error whenever I try to fetch data, I don't know why, it should show me posts but it gives me an error and a white page!
This the Posts.jsx
code
import Post from "../post/Post";
import "./posts.css";
export default function Posts({ posts }) {
return (
<div className="posts">
{posts.map((p) => (
<Post post={p} />
))}
</div>
);
}
This the Home.jsx
code
import { useEffect, useState } from "react";
import Header from "../../components/header/Header";
import React from 'react'
import "./home.css"
import Posts from "../../components/posts/Posts";
import Sidebar from "../../components/sidebar/Sidebar";
import axios from "axios"
export default function Home() {
const [posts, setPosts] = useState([]);
useEffect(()=>{
const fetchPosts = async ()=>{
const res = await axios.get("/posts")
setPosts(res.data)
}
fetchPosts()
}, [])
return (
<>
<Header />
<div className="home">
<Posts />
<Sidebar />
</div>
</>
);
}
I don't know why I get this error if anyone can help !
CodePudding user response:
You are not passing data(posts) to the Posts component.
<Posts posts={posts}/>
For the safer side what you can do
- Add default value of posts
- Add nullish coalescing operator
export default function Posts({ posts = [] }) {
return (
<div className="posts">
{posts?.map((p) => (
<Post post={p} />
))}
</div>
);
}
CodePudding user response:
import Post from "../post/Post";
import "./posts.css";
export default function Posts({ posts }) {
return (
<div className="posts">
{posts && posts.map((p) => (
<Post post={p} />
))}
</div>
);
}
The reason why you are getting this error because the post take some time to get load because it returns a promise so you must for that to resolve in order to render to post the best practice is define a variable loading and show spinner until it resolve