1

So I am trying to get a timestamp on the time a post is made, but fire.database.ServerValue.TIMESTAMP doesn't seem to be working in the addTicket function. When I post the ticket, it doesn't load to the Pending page, and just has variables ticketTitle & ticketBody in the Ask URL. I think I am just confused on how the timestamp works in firebase. How do I properly add the timestamp of the post to the database tuple?

Ask.js:

import React, { Component } from 'react';
import AskForm from '../../components/AskForm.js';
import fire from '../../config/Fire.js';
import { Link, withRouter } from 'react-router-dom'

class Ask extends Component {
  constructor(props){
    super(props);
    this.addTicket = this.addTicket.bind(this);
    this.database = fire.database().ref().child('tickets');

    this.state = {
      tickets: [],
      userId: this.props.user.uid
    }
  }

  componentDidMount(){
    fire.database().ref('/users/' + this.props.user.uid).once('value').then(function(snapshot) {
      var FirstName = (snapshot.val() && snapshot.val().userFirstName);
      // ...
      console.log(FirstName);
    }); 
  }

  addTicket(title, body){
    this.database.push().set({ ticketUserId: this.props.user.uid, ticketTitle: title, ticketBody: body, ticketStatus: 'pending', ticketTime: fire.database.ServerValue.TIMESTAMP});
    alert("Your question has been submitted.")
    this.props.history.push('/pending')
  }

  render() {
    return (
      <div>
        <div className="m-container">
        </div>
        <div>
          <AskForm addTicket={this.addTicket} />
        </div>
      </div>
    );
  }
}

export default withRouter(Ask);

AskForm.js

import React, { Component } from 'react';

class AskForm extends Component{
    constructor(props){
        super(props);
        this.state = {
            ticketBody: '',
            ticketTitle: ''
        };
        this.handleChange = this.handleChange.bind(this);
        this.writeTicket = this.writeTicket.bind(this);
    }

    // When the user input changes, set the ticketTitle or ticketBody
    // to the value of what's in the input box.

    handleChange(e) {
        this.setState({ [e.target.name]: e.target.value });
    }

    writeTicket(){
        if(this.state.ticketTitle === '' || this.state.ticketBody === ''){
            alert('Please complete all fields.')
        } else {
            // Call a method that sets the ticketTitle and ticketBody for a ticket to
            // the value of the input
            this.props.addTicket(this.state.ticketTitle, this.state.ticketBody);
            // Set inputs back to an empty string
            this.setState({
                ticketBody: '',
                ticketTitle: ''
            })
        }

    }

    render(){
        return(
            <div class="s-container">
                <form>
                    <label for="ticketTitle">Title: </label>
                    <input
                    id="ticketTitle"
                    name="ticketTitle"
                    type="text"
                    placeholder="A short sentence to identify your issue" 
                    value={this.state.ticketTitle}
                    onChange={this.handleChange}
                    /> 
                    <br/>
                    <br/>
                    <label for="ticketBody">Description: </label>
                    <textarea
                    id="ticketBody"
                    name="ticketBody"
                    placeholder="Placeholder" 
                    value={this.state.ticketBody}
                    onChange={this.handleChange}
                    /> &nbsp;
                    <button 
                    className="m-btn"
                    onClick={this.writeTicket}>
                    Submit
                    </button>
                </form>
            </div>
        )
    }
}

export default AskForm;
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
douglasrcjames
  • 1,133
  • 3
  • 17
  • 37

2 Answers2

1

Revisited my question:

I need to import firebase directly using import * as firebase from 'firebase'; instead of from my config file. Then just pushed the time value to the database with my other values. See below for example.

Code:

import * as firebase from 'firebase';

  addMessage(body){
    this.questionDatabase.child(this.state.questionId).child('messages').push().set({ 
        messageUserId: fire.auth().currentUser.uid, 
        messageBody: body,
        time: firebase.database.ServerValue.TIMESTAMP
    });
  }
douglasrcjames
  • 1,133
  • 3
  • 17
  • 37
  • Yeah i did this too but firebase warns you should not import the entirety of firebase into your project with the console error: "Warning: It looks like you're using the development build of the Firebase JS SDK" There must be a better way... – Quinma Apr 08 '20 at 19:22
  • @Quinma true, since I answered this question, I have learned that, there's a few posts already on SO that fix that issue. – douglasrcjames Apr 09 '20 at 00:20
  • 1
    I asked this and got an answer that works: https://stackoverflow.com/questions/61109729/firebase-firestore-server-timestamp-without-importing-all-of-firebase-to-my-web/61109827#61109827 – Quinma Apr 09 '20 at 16:58
1

This works to create a timestamp client side is using firestore: (In this case I export it from my main firebase.js file)

import firebase from "firebase/compat/app";
import "firebase/compat/firestore";

export const serverStamp = firebase.firestore.Timestamp

To use it after importing serverStamp:

var stampNow = serverStamp.now()
August Kimo
  • 1,503
  • 8
  • 17