Search code examples
jsonobjectgoogle-cloud-firestoreclass-constructors

Firestore timestame using toDate() is not a function error


I have firestore data with timestamp.

User will backup data as JSON file - Export-Function

const dataStr = JSON.stringify(todos);
let dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr);
let fileName = 'data.json';
let linkElement = document.createElement('a') as HTMLAnchorElement;
linkElement.setAttribute('href', dataUri);
linkElement.setAttribute('download', fileName);
linkElement.click();

Then User will restore data- Import-Function

const uploadFile = fileInput.files[0];
const fileReader = new FileReader();
fileReader.onload = async (e) => {
const dataStr = e.target?.result as string;
const newDatas = JSON.parse(dataStr) as todosProps[];
console.log(newDatas);
settodos([
  ...todos,
  ...newDatas
]);
try {
  newDatas.map(async (d) => {
    await setDoc(doc(collectionRef, d.id.toString()), {
      ...d,
    });
  });
  console.log('finish import');      
} catch (error) {
  console.error(error);
}

I noticed that , firestore timestamp object value have different constructor method when convert to JSON.

so I cannot use firestore function like " .toDate() .toMillis " in imported one . So why it is different with original Timestamp. May be I converted original data to JSON . Or my code is wrong ?

constructor class vs object

I have no idea to try . I was expecting to get correct order .


Solution

  • Credits @Rahul Kumar

    for anyone who is having toDate() is not a function error might be because you are using it on a JSON object. You can simply use the timestamp object received from firebase, or If you are not able to use it directly then To convert it back to timestamp object you can do this:

    const timestamp = new firebase.firestore.Timestamp(jsonTimestamp.seconds, jsonTimestamp.nanoseconds)
    

    now doing timestamp.toDate() will work