0

Hello I'm working a real time chat app for my portfolio, I'm having trouble with converting a timestamp I receive from firebase store.

import {serverTimestamp} from 'firebase/firestore';

I looked at this question similar to my problem How do I convert a Firestore date/Timestamp to a JS Date()?, and I tried to use the solutions that were given, and they didn't quite work as intended. I tried using new date to convert the time stamp to a javascript date directly, and it works well for the older messages I made before adding timestamps, but for new messages I try to create I get errors.

this is the timestamp format I receive from firestore.

createdAt: August 2, 2023 at 7:03:09 PM UTC-5

here is my code.

  const handleSubmitForm = async (e) =>{
    e.preventDefault();
    if(message === "") return;

    // this is the firebase timestamp I'm trying to convert.
    const messageDate = new Date(serverTimestamp);
    console.log(messageDate)
    
    //this deconstucts the firebase auth.currentUser array
    const {uid, displayName, photoURL} = auth.currentUser;
    //this fulfills the promise to add a document to the "messages" collection with the currently logged in users message and profile info. 
    await addDoc(messagesRef, {
      text: message,
      createdAt: messageDate,
      user: displayName,
      userPic: photoURL,
      room,
      uid,
    });
    setMessage("")
  }

this is the jsx "messages" is just referring to useState that holds the firebase database that I'm mapping through.

{messages.map((message) =>(
        <p className='message-timestamp'>-{message.createdAt.toDate().toDateString()}</p>
))}

as I said every time I try to submit a new message I get this error "index.esm2017.js:6342 Uncaught (in promise) RangeError: Invalid time value" and I tried to console log "message date" and it returns "invaild Date. What am I doing wrong? and How can I convert the firebase timestamp to a javaScript object.

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121

1 Answers1

0

If I correctly understand your functional requirement you need to use the serverTimestamp() method as explained in the documentation:

import { addDoc, serverTimestamp } from "firebase/firestore";

// ...

await addDoc(messagesRef, {
      text: message,
      createdAt: serverTimestamp(),
      user: displayName,
      userPic: photoURL,
      room,
      uid,
});

Note that the SO answer you refer to in your question is about transforming a Timestamp received (i.e. read) from Firestore in your frontend/application. Not about writing to Firestore.

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121