Why timestamp is not saved to React state object?

316 views Asked by At

I am trying to save the date as a timestamp in Firebase, but for some reason, the timestamp does not save to state from form onChange handler...

const [event, setEvent] = useState({});

function handleDate(e) {
  e.persist();
  let d = e.target.value;
  console.log('date1', d); //date1 2020-10-13
  let dd = new Date(d);
  console.log('date2', dd); // Tue Oct 13 2020 02:00:00 GMT+0200 (Central European Summer Time)
  let ddd = dd.getTime() / 1000;
  console.log('timestamp ', ddd); // timestamp  1602547200
  setEvent({...event, date_ts: ddd});
  console.log('event timestamp', event.date_ts); //null
  setEvent({...event, date: e.target.value});
  console.log('event date', event.date); // empty string
}

Finally the event.date property is saved correct, but event.date_ts is null. Why?? And secondly... Why the "event date" console log from the handler is an empty string but the date gets saved? Thanks

EDIT:

It is right now very basic Firebase save:

    const saveNewEvent = (e) => {
        e.preventDefault()
        console.log("save event", event) //HERE the time_ts is "null"
        firebase.firestore().collection(event.category).add({
            event
        })
        setEvent({ ...defalut_event })
    }

...so it looks like it is some React weirdness, nothing to do with Firebase... (or maybe my incompetence, rather ;)

1

There are 1 answers

5
Sam YC On

You can read this for more info.

Basically when you execute this:

setEvent({ ...event, date_ts: ddd })

Reactjs will not update the event object immediately. For performance reason, it will batch multiple setEvent and call render once.

So when you call this:

console.log("event timestamp", event.date_ts) //null

The event is not the latest value which you set in previous line yet.

If you want to get latest value, you need to use lifecycle hook, as described here.