To hopefully help you with server timestamp I have modified the simple react-firebase-hook app created as an answer for this question: https://stackoverflow.com/a/60504303/610053
- I’ve updated my Firebase class with an extra method called serverTimestamp:
class Firebase {
constructor() {
app.initializeApp(firebaseConfig);
this.realtimedb = app.database();
this.firestore = app.firestore();
this.serverTimestamp = app.firestore.FieldValue.serverTimestamp;
}
}
const FirebaseContext = React.createContext(null);
const App = () => {
const firebase = React.useContext(FirebaseContext);
const [counter, setCounter] = React.useState(-1);
const [timestamp, setTimestamp] = React.useState(null);
React.useEffect(() => {
const unsubscribe = firebase.firestore.collection("counters").doc("simple").onSnapshot(documentSnapshot => {
if(documentSnapshot) {
const data = documentSnapshot.data();
console.log("New data", data);
setCounter(data.value);
if(data.updatedAt) {
let initDate = new Date(0);
initDate.setSeconds(data.updatedAt.seconds);
setTimestamp(initDate);
}
}
})
return () => unsubscribe;
}, []);
const handleIncrement = () => {
firebase.firestore.collection("counters").doc("simple").update({
value: counter + 1,
updatedAt: firebase.serverTimestamp(),
});
}
return (<div>
<div>
Current counter value: {counter}. Updated: { timestamp ? timestamp.toString() : "Never?.." }
</div>
<div>
<button onClick={handleIncrement}>Increment</button>
</div>
</div>);
};
0
solved Firebase: how to add timestamp to database in firestore – where react context api is used