Rendering a firestore timestamp in react

删除回忆录丶 提交于 2020-04-28 21:17:02

问题


I have been trying for months to figure out how to display a firestore timestamp in react.

In December 2019, the solution I accepted on this post worked. It no longer works. I'm back to stuck.

I have a firebase.js helper to record dates with:

class Firebase {
  constructor() {
    app.initializeApp(config)
    this.firestore = app.firestore();
    this.auth = app.auth();
    this.serverTimestamp = app.firestore.FieldValue.serverTimestamp;


  }

I use that helper in forms to record the date an entry is created like so:

  await Firebase.firestore.collection("blog").doc().set({ 
    title: values.title,    
    createdAt: Firebase.serverTimestamp()

That correctly saves a date into the firestore document that looks like this:

When I hover over the date, it shows 'timestamp'. I am able to order the data returned from firestore by reference to the createdAt date - so it's curious that the timestamp can be used to sort the documents but cannot be used to print the date on the screen.

When it then comes to outputting the date, I am back to getting all the same errors I reported in the previous post - but the solution that worked in December, no longer works. I have seen a discussion in the firebase slack channel that a recent release of firebase has had some unintended consequences - is there any way to check if broken timestamps is one of them?

When I try:

   {currentPost.createdAt.toDate().toISOString()}

TypeError: Cannot read property 'toDate' of undefined

When I try:

   {currentPost.createdAt.toDate()}

TypeError: Cannot read property 'toDate' of undefined

When I try:

   {new Date(currentPost.createdAt.seconds * 1000).toLocaleDateString("en-US")}

TypeError: Cannot read property 'seconds' of undefined

When I try (I know this won't work but just trying to find insights that might help solve this problem):

   {currentPost.createdAt}

Error: Objects are not valid as a React child (found: object with keys {seconds, nanoseconds}). If you meant to render a collection of children, use an array instead.

I have seen some posts which say the date is undefined because the call on firebase hasn't returned a value yet, but when I console.log the whole currentPost, I get a value for created At, which is:

createdAt: t seconds: 1586495818 nanoseconds: 888000000

The part of this that looks suspicious is the "t". Does it represent something that I'm supposed to do something with in order to access the timestamp? Does anyone know how to investigate what the 't' represents?

I have seen this post and this post, and note that each of the answers to it suggest that the .toDate() extension should help to convert a firestore timestamp to something that can be output. None of those solutions work here.

Has anyone figured out a current solution that allows to both save and output a date from firestore?


回答1:


Strange - I don't understand why or how this works, but it does.

I changed the useEffect to be async - as follows.

function ReadBlogPost () {
    const [loading, setLoading] = useState(true);
    const [currentPost, setCurrentPost] = useState({});
    let { slug } = useParams();


    useEffect(() => {

        const fetchData = async() => {

            try {

                const response = await Firebase.firestore
                    .collection("blog")
                    .doc(slug)
                    .get();

                console.log('response', response);

                let data = { title: 'not found' };

                if (response.exists) {
                    data = response.data();
                }

                setCurrentPost(data);
                setLoading(false);

            } catch(err) {
                console.error(err);
            }

        };

        fetchData();

    }, []);

Then in the render, I can use:

 {!loading && new Date(currentPost.createdAt.seconds * 1000).toLocaleDateString("en-US")}

Fingers crossed this works for more than a few months.



来源:https://stackoverflow.com/questions/61166977/rendering-a-firestore-timestamp-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!