1
votes

Before this, I'm using Snapshot and try to map it. But it failed for a single document. After I read back the documentations from firebase. They recommend using this way for a single document. But I don't know how to make it readable on the site rather than console. I want to send data on the title and essay.

const { id } = useParams()

useEffect(() => {
    db.collection("posts").doc(id).get().then(doc => {
        const newData = doc.data();
        console.log(newData);
    });
}, []);

return (
    <div className="log">
            <article className="log-details">
                <div className="author-pic clearfix">
                    <img src={profile} alt="" />
                </div>
                <div className="log-preview">
                    <div class="cover"></div>
                    <h2 className="title clearfix">title here</h2>

                    <div className="details ">
                        <img src={One} alt="" />
                        <p className="essay">essay here</p>
                    </div>
                </div>
            </article>
    </div>
)
1

1 Answers

1
votes

To display the post Data use useState and set the postData with setPostData(newData). Then you can read the postData values with {postData.title} and {postData.essay} in the return statement.

Dont forget to import useState with import React, { useState, useEffect } from "react".

const { id } = useParams()
const [postData, setPostData] = useState("");

useEffect(() => {
    db.collection("posts").doc(id).get().then(doc => {
        const newData = doc.data();
        setPostData(newData);
        console.log(newData);
    });
}, []);

return (
    <div className="log">
            <article className="log-details">
                <div className="author-pic clearfix">
                    <img src={profile} alt="" />
                </div>
                <div className="log-preview">
                    <div class="cover"></div>
                    <h2 className="title clearfix">{postData && postData.title}</h2>

                    <div className="details ">
                        <img src={One} alt="" />
                        <p className="essay">{postData && postData.essay}</p>
                    </div>
                </div>
            </article>
    </div>
)