Home > Software engineering >  Uncaught TypeError: Cannot read properties of undefined (reading 'map') Errors
Uncaught TypeError: Cannot read properties of undefined (reading 'map') Errors

Time:05-21

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 error I get enter image description here

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

  1. Add default value of posts
  2. 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

  • Related