title: Firebase: how to add timestamp to database in firestore - where react context api is used
body: <p>I am trying to add a time stamp to my firebase form data in my react app.</p>
  
  <p>The app uses react context api to wrap the app in a FirebaseContext.Provider as follows:</p>
  
  <pre><code>ReactDOM.render(
  
    &lt;FirebaseContext.Provider value={new Firebase()}&gt;
      &lt;App /&gt;
  
    &lt;/FirebaseContext.Provider&gt;,
    document.getElementById('root'),
  );
  </code></pre>
  
  <p>The context provider has:</p>
  
  <pre><code>import React from 'react';
  const FirebaseContext = React.createContext(null);
  export const withFirebase = Component =&gt; props =&gt; (
    &lt;FirebaseContext.Consumer&gt;
      {firebase =&gt; &lt;Component {...props} firebase={firebase} /&gt;}
    &lt;/FirebaseContext.Consumer&gt;
  );
  export default FirebaseContext;
  </code></pre>
  
  <p>Then, each component that needs firebase is wrapped in the consumer, as follows:</p>
  
  <pre><code>import Firebase, { withFirebase } from "../../firebase"
  
  export default withFirebase(Register)
  </code></pre>
  
  <p>In my submit handler, I'm trying to add a timestamp to the form data:</p>
  
  <pre><code>handleCreate = () =&gt; {
  
      const { form } = this.formRef.props;
      form.validateFields((err, values) =&gt; {
        if (err) {
          return;
        }
        // console.log("does it know what firebase is?", this.props.firebase.db);
      //   console.log("try time", this.props.firebase.db.FieldValue.serverTimestamp());
        console.log("it can get this far");
        console.log(this.props.firebase.firestore.FieldValue.serverTimestamp());
        console.log("it can get this far 2");
  
        const payload = {
          ...values,
          // role: formState.role.value,
          // created: this.props.firebase.fieldValue.serverTimestamp(),
          //  console.log("try to get a timestamp to work", this.props.firebase.serverValue.TIMESTAMP),
          // console.log("it can get to payload"),
  
          // createdAt: this.props.firebase.serverValue.TIMESTAMP
          // createdAt: this.props.firebase.FieldValue.serverTimestamp
  
          // createdAt: this.props.firebase.firestore.FieldValue.serverTimestamp(),
        }
        // console.log("formvalues", payload);
  
  
        // console.log('Received values of form: ', values);
        this.props.firebase.db
            .collection("preregistrations")
            .add(payload)
            // .set(FieldValue.serverTimestamp())
  
            // .add (createdAt: this.props.firebase.firestore.FieldValue.serverTimestamp());
  
            // .add(
            //   createdAt: this.props.firebase.firestore.FieldValue.serverTimestamp()
            // )
  
            // .then(docRef =&gt; {
              // resetForm(initialValues);
  
            // })
            .then(e =&gt; this.setState({ modalShow: true }))
            .catch(error =&gt; {
              console.error("Error adding document: ", error);
            });
  
        form.resetFields();
        this.setState({ visible: false });
      });
  </code></pre>
  
  <p>};</p>
  
  <p>My firebase config is setup as follows.</p>
  
  <pre><code>import app from 'firebase/app';
  import 'firebase/auth';
  import 'firebase/firestore';
  import firestore from "firebase/firestore";
  
  
  class Firebase {
    constructor() {
      app.initializeApp(config).firestore();
      this.auth = app.auth();
      // this.db = app.firebase.database()
      this.db = app.firestore();
  
    }  
  </code></pre>
  
  <p>Previously, this has worked:</p>
  
  <pre><code>createdAt: this.props.firebase.firestore.FieldValue.serverTimestamp()
  </code></pre>
  
  <p>The <a href="https://firebase.google.com/docs/reference/js/firebase.firestore.FieldValue" rel="nofollow noreferrer">firebase documents</a> say that FieldValue works with .set and .update. Where those of the attempts I'm making include the "FieldValue" step, I'm trying to use it with .add</p>
  
  <p>The <a href="https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp" rel="nofollow noreferrer">timestamp documentation</a> uses this format to give a timestamp:</p>
  
  <pre><code>firebase. firestore.Timestamp
  </code></pre>
  
  <p>I've tried following this format as a line item in the payload as well as a step in sending data to the database:</p>
  
  <pre><code>createdAt: this.props.firebase.firestore.Timestamp,
  </code></pre>
  
  <p>Another approach that has previously worked is set out in <a href="https://stackoverflow.com/questions/56035174/firebase-firestore-createdat-timestamps-react">this post</a>. The answer and the firebase documents suggest that the timestamps only work with .set and .update, whereas I'm trying to use it with .add. Perhaps something has changed in firebase so the it no longer works with .add - but I tried adding a .set step after my .add step and that didn't work either.</p>
  
  <pre><code>this.props.firebase.db
            .collection("preregistrations")
            .add(payload)
            .set(FieldValue.serverTimestamp())
  </code></pre>
  
  <p>I have a tutorial that recommends using this approach.</p>
  
  <pre><code>console.log("try timestamp",  this.props.firebase.serverValue.TIMESTAMP),
  </code></pre>
  
  <p>It doesn't work. No error message gets generated and the console log does not run -the form just hangs and does not submit.</p>
  
  <p>This tutorial comes with a book that directs to this tutorial for moving from realtime database to firestore. The only remark it makes about using timestamps is to say:</p>
  
  <blockquote>
    <p>The set up for using timestamps, in this case for the createdData
    property for our message entities, has also changed slightly.</p>
  </blockquote>
  
  <p>It does not disclose what the slight change is - but it does give 2 clues.</p>
  
  <p>First - there is a <a href="https://github.com/the-road-to-react-with-firebase/react-firestore-authentication/blob/master/src/components/Messages/Messages.js" rel="nofollow noreferrer">repo</a> linked to the post which has a timestamp in it like so:</p>
  
  <pre><code>  createdAt: this.props.firebase.fieldValue.serverTimestamp().
  </code></pre>
  
  <p>This is the same as the attempt previously made in the form submit handler.</p>
  
  <p>Second - the post references this bit of the <a href="https://firebase.google.com/docs/firestore/" rel="nofollow noreferrer">firestore documentation</a> for how to figure out changing from realtime database to firestore.  That bit of the documentation doesn't have anything to say about making a timestamp in firestore. The documentation does have an example application for <a href="https://github.com/firebase/friendlyeats-web" rel="nofollow noreferrer">FriendlyEats</a> which has code with a table with a timestamp.  It has:</p>
  
  <pre><code> rating.timestamp = new Date();
  </code></pre>
  
  <p>It also has references to something removing timestamps from snapshots but I can't find the code before the example was updated to remove them so that I can find out how to add them.</p>
  
  <p><a href="https://stackoverflow.com/questions/52462240/react-firebase-timestamp-usage">This post</a> suggests that it is necessary to import * as firebase to get the timestamps to work. If I import that, then I get a warning saying not to use the * except in development. Does this mean there is a separate package other than the ones I have imported in my firebase config (as below) that is needed to make timestamps work - and if there is - does it have a specific name - or is the * import necessary to get timestamps to work?</p>
  
  <pre><code>import app from 'firebase/app';
  import 'firebase/auth';
  import 'firebase/firestore';
  import firestore from "firebase/firestore";
  </code></pre>
  
  <p>I tried following the approach in that post and:</p>
  
  <ol>
  <li><p>imported * in the form file:</p>
  
  <p>import * as firebase from 'firebase';</p></li>
  <li><p>added the following to the payload:</p>
  
  <p>createdAt: this.props.firebase.db.Timestamp,</p></li>
  </ol>
  
  <p>It doesn't work - no error messages - but the form hangs when it gets to that step.</p>
  
  <p><strong>NEXT ATTEMPT</strong></p>
  
  <p>NEXT, I tried to use:</p>
  
  <pre><code>createdAt: this.props.firebase.fieldValue.serverTimestamp(),
  </code></pre>
  
  <p>This is because this tutorial (which loosely refers to changes requires to use dates with firestore includes a link to a <a href="https://github.com/the-road-to-react-with-firebase/react-firestore-authentication/blob/master/src/components/Messages/Messages.js" rel="nofollow noreferrer">repo</a> that uses this format).</p>
  
  <p>Then in firebase.js I have a helper as:</p>
  
  <pre><code>class Firebase {
    constructor() {
      app.initializeApp(config).firestore();
  
  
      /* Firebase APIs */
      this.auth = app.auth();
      this.db = app.firestore();
  
      /* helpers */
      this.fieldValue = app.firestore.FieldValue;
  </code></pre>
  
  <p>Note that in the helper, FieldValue is upper case for Field.</p>
  
  <p>When I try this, I get an error that says:</p>
  
  <blockquote>
    <p>FirebaseError: Function DocumentReference.set() called with invalid
    data. Unsupported field value: undefined (found in field createdAt)</p>
  </blockquote>
  
  <p>When I try making the createdAt use similar casing in the timestamp creator (which the answer to <a href="https://stackoverflow.com/questions/50361962/cloud-functions-cloud-firestore-error-cant-get-servertimestamp">this post</a> suggests is correct), I try:</p>
  
  <pre><code>createdAt: this.props.firebase.FieldValue.serverTimestamp(),
  </code></pre>
  
  <p>This also fails. No error message but the form does not submit.</p>
  
  <p><strong>NEXT ATTEMPT</strong></p>
  
  <p>When I move the createdAt step out of the payload and just try to use in the submit handler step when the user is created in the database, like so:</p>
  
  <p>TypeError: Cannot read property 'serverTimestamp' of undefined</p>
  
  <pre><code>return this.props.firebase.user(authUser.user.uid).set(
              {
                name: values.name,
                email: values.email,
                // createdAt: values.createdAt,
                createdAt: this.props.firebase.FieldValue.serverTimestamp(),
  
              },
              { merge: true }
            );
          })
  </code></pre>
  
  <p>the user set step is ignored by firebase (it does not create the record). The console error says:</p>
  
  <pre><code>TypeError: Cannot read property 'serverTimestamp' of undefined
  </code></pre>