Search code examples
javascriptreactjsmap-functionreact-map-gl

Why my code is not mapping through the array of object in react using id as the key?


I am able to print the blog array in the console and it includes the object. I want to use the object components by mapping through the id as the key but I am not able to get inside the map function. I was able to use the same map structure in my another component of my app but this one is not working. I tried map function in different ways but I am not able to get this one fixed. Can I get some review and advise on my code?

import {colRef} from "./firebase";
import { useParams } from "react-router-dom";
import {doc, onSnapshot} from 'firebase/firestore'
import { useEffect, useState } from "react";

    const BlogDetails = () => {
    
        const{id}=useParams();
        const[blog,setBlog] = useState(null);
    
        ///Getting single document.
        useEffect(() => {
    
            const docref= doc(colRef,id);
            let document =[];
            
            onSnapshot(docref,(doc) => {
                document.push({...doc.data(),id:doc.id})
            })
            ///console.log(document)
            if(document)
            {
                setBlog(document);
            }
    
        },[id]);  
        
        return (
            <div className="blog-details">
                
                {blog && (console.log(blog))}
                {blog && (blog.map((blog) => (
                    <div className="blog-info" key={blog.id}>
                        {console.log('Inside blog-info')}
                        {console.log(blog)}
                        <h2>{blog.title}</h2>
                        <p>Written by {blog.author}</p>
                        <div>{blog.body}</div>
                        <button>delete</button> 
                    </div>
                )))}            
            </div>   
        );
    }
     
    export default BlogDetails;

Solution

  • This code is asynchronouse and it can't work like this:

    const docref= doc(colRef,id);
    let document =[];
    
    onSnapshot(docref,(doc) => {
      document.push({...doc.data(),id:doc.id}) // than this
    })
    if(document)
    {
      setBlog(document); // this runs first
    }
    

    It should look more like that:

    const docref= doc(colRef,id);
    
    onSnapshot(docref,(doc) => {
      setBlog({...doc.data(),id:doc.id}))
    })