简体   繁体   中英

How to get/generate current Timestamp in firebase firestore in React

I am using Firebase Firestore database in my current project and have to add documents from my front-end react for this i need current timestamp.

import * as firebase from "firebase";
import React, {useState} from 'react';

const [time, setTime] = useState({''}) //here i need current timestamp from firebase.

well you need to import firestore from firebase, don't use firebase.firestore.FieldValue.serverTimeStamp it won't work

here is the working example

import {firestore} from "firebase";

const timestamp = firestore.FieldValue.serverTimestamp();
firebase.initializeApp(firebaseConfig);
const projectFirestore = firebase.firestore();
const timestamp = firebase.firestore.FieldValue.serverTimestamp;

firebase.initializeApp(firebaseConfig); const timestamp = firebase.firestore.FieldValue.serverTimestamp;

please also note that as much as @shubham Takode answer is true, firebase firestore current timestamp doesn't get populated on the client side, so it will do you no good trying to use it in the react useState() management.

import * as firebase from "firebase";
import React, {useState} from 'react';

firebase.firestore
    .collection('user')
    .doc('userid1')
    .set({
           username: "first user",
           email: "user@email.com",
           time: firebase.firestore.FieldValue.serverTimestamp() // This sets a placeholder in your record that get authomatically populated with the serverTime once it gets to your firestore db.
    }).then(/*do somethings on success*/).catch(err => {/*do somethings on err*/})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM