Getting an Empty array from the firestore

  firebase, javascript, reactjs

This is my code for LeftBar Component
I want to get the data stored in the "contacts" document in the firebase but getting an empty array. Idk know why this is happening. And one thing if anyone can tell me how to do it with class-based component ( how to use that use effect thing into ComponentDidMount and ComponentDidUpdate) as I have two other class Components which are also using the same functionality Please help

import React, {useState , useEffect}  from "react";
import { Avatar, IconButton } from "@material-ui/core";
import AddCircleIcon from "@material-ui/icons/AddCircle";
import MoreIcon from "@material-ui/icons/More";
import ChatBubbleOutlineIcon from "@material-ui/icons/ChatBubbleOutline";
import SearchIcon from '@material-ui/icons/Search';
import LeftChats from './LeftChats';
import "./LeftBar.css";
import db from './firebase'

function LeftBar () {
  const [contacts, setContacts] = useState([])

  useEffect(() => {
    db.collection("contacts").onSnapshot((snapshot)=> setContacts(
      snapshot.docs.map((doc)=> ({
        id : doc.id,
        data : doc.data(),
      }))
    ))
  },[])
  
  console.log(contacts);

    return (
      <div className="leftbar">
        <div className="left-header">
          <Avatar />
          <div className="left-right-header">
            <IconButton>
            <AddCircleIcon />
            </IconButton>
            <IconButton>
            <MoreIcon />
            </IconButton>
            <IconButton>
            <ChatBubbleOutlineIcon />
            </IconButton>
          </div>
        </div>

        <div className="left-search">
            <div className='input-container'>
            <SearchIcon/>
            <input type='text' placeholder='Search...'/>
            </div>
        </div>
       

        <div className="left-chats">
{
              contacts.map( contact =>( 
                <LeftChats key={contact.id} id = {contact.id} username= 
                 {contact.data.name}/>
              ))
            }
          
        </div>
      </div>  
    );
  
}

export default LeftBar;

This is my LeftChat Component

import React, { Component } from 'react'
import { Avatar} from "@material-ui/core";


class LeftChats extends Component {
   constructor(props) {
       super(props)
   
       this.state = {
            data : ''
       }
   }
render() 
    {
        console.log(this.props)
        return  (
            <div className='leftchats'>
                <Avatar/>
                <div className='chats-info'>
                <h2>{this.props.username}</h2>
                <p>Some text message...</p>
                </div>
            </div>
        ) 
    }
}

export default LeftChats

Source: Ask Javascript Questions

LEAVE A COMMENT