Home > Back-end >  TypeError: Cannot read properties of undefined (reading 'profilePic'), react
TypeError: Cannot read properties of undefined (reading 'profilePic'), react

Time:11-14

I I am trying to fetch data from the firestore cloud but get error "TypeError: Cannot read properties of undefined (reading 'profilePic')" Why is it saying undefined yet it is defined?

  import React, {useState, useEffect} from 'react';
  import Post from './Post';
   import db from '../firebase';
  
  const Feed = ({profilePic, message, timestamp, username, image}) => {
  const [posts, setPosts]  =useState([]);

  //realtime database connection
  useEffect(() => {
  db.collection('posts')
 .orderBy('timestamp','desc')
 .onSnapshot((snap) => (
  setPosts(snap.docs.map((doc) => ({...doc.data(), id: doc.id })))
  ));
   }, []);
    
   return (
    <div className='feed'>
      {posts.map((post)=>(
        <Post
        key={post.id}
        profilePic={post.data.profilePic}
        message={post.data.message}
        timestamp={post.data.timestamp}
        username={post.data.username}
        image={post.data.image}
        />
      ))}
    </div>
   );
  }

  export default Feed;

CodePudding user response:

You are trying to read profilePic from posts.data which is undefined. This value is being set in useEffect method.

I think the problem is in this line

setPosts(snap.docs.map((doc) => ({...doc.data(), id: doc.id }))).

Try this: Assign the result of this code in a separate variable and then see the value of that variable in console. Check if the data in the variable is being created properly.

useEffect(() => {
  db.collection('posts')
 .orderBy('timestamp','desc')
 .onSnapshot((snap) => {
   let p = snap.docs.map((doc) => ({...doc.data(), id: doc.id }));
   console.log("POSTS", p) // check the value in console
   setPosts(p);
  }));
   }, []);

CodePudding user response:

try this: setPosts(snap.docs.map((doc) => ({ id: doc.id, data: doc.data()})))

and add optional chaining

{posts?.map((post)=>(
    <Post
    key={post.id}
    profilePic={post.data.profilePic}
    message={post.data.message}
    timestamp={post.data.timestamp}
    username={post.data?.username}
    image={post.data?.image}
    />
  ))}
  • Related