0

I have dealt with this issue with Firestore/React for a bit where I am trying to load user data in componentDidMount() from Firestore from a value that doesn't exist in the document. The only way I know how to fix this is by initializing all values for a given object to empty even if they are not being used yet. Such as setting currentWorker object as I did below:

tickets: { 
  ID12345: {
    title: "example title",
    currentWorker: {
       name: ""
    }
  }
}

I would like to leave it undefined until it's needed as I do simply below:

tickets: { 
  ID12345: {
    "example title"
  }
}

Only problem for this case is that I do not know how to test for currentWorker object being set without throwing a TypeError: Cannot read property 'name' of undefined. I have tried to test for undefined objects in multiple ways like I do in the example below, but I get the same error.

if (typeof(doc.data().currentWorker.name ) !== 'undefined' || doc.data().currentWorker.name != null) {
  firestore.collection("tickets").doc(doc.data().currentWorker.name )
.get().then(function(doc) {
  if (doc.exists) {
      if (this._isMounted) {
        this.setState({
          worker: doc.data()
        })
      }
  } else {
      console.log("Grabbing currentWorkerfailed");
  }
}.bind(this)).catch(function(error) {
    console.log("Error grabbing currentWorker: ", error);
});
} else {
  console.log('Undefined or Null')
}

How do I test for a non-existent object in a document without throwing this error? Or do I always need to initialize documents with the fields I want to test for in my React app?

douglasrcjames
  • 1,133
  • 3
  • 17
  • 37

0 Answers0