1

Trying to render Footer component using inline if-else to avoid passing undefined data from Firebase, somehow it is passing those props, and Footer component yelling about undefined props.

this.state = {
  location: {},
  hours: {}
};

componentDidMount() {
  db.collection('location').get().then(snapshot => {
    snapshot.docs.forEach(doc => {
      this.setState({
        location: { ...doc.data()
        }
      })
    })
  });

  db.collection('hours').get().then(snapshot => {
    snapshot.docs.forEach(doc => {
      this.setState({
        hours: { ...doc.data()
        }
      })
    })
  });
}

render({
    {
      (this.state.hours) ? < Footer hours = {
        this.state.hours
      }
      location = {
        this.state.location
      }
      /> : null }
    })
AsthaUndefined
  • 1,111
  • 1
  • 11
  • 24
Verthon
  • 2,937
  • 3
  • 20
  • 32

4 Answers4

2

It looks like you are initializing this.state.hours to the empty object {}

An empty object will evaluate to true in Javascript

if ({}) console.log("yes"); // Prints "yes"

Perhaps you should initialize it to false instead

this.state={
  location: {},
  hours: false
};
Adam Prax
  • 6,413
  • 3
  • 30
  • 31
2

The way your code is now, this.state.hours will never be falsey. An empty object is truthy. See All falsey values in JavaScript for more details.

You either need a separate boolean in state letting you know whether or not hours has been loaded or you need to check for something more specific within this.state.hours. Another option would be to initialize this.state.hours to false.

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198
1

You shouldn't check state like this (this.state.hours)? it will be false when this.state.hours is 0 or '', but it will be true when this.state.hours is {}.
Try using null instead, with condition == null (to check if null or undefined) or === null to check if null:

this.state={
  location: {},
  hours: null
};

 componentDidMount(){
 db.collection('location').get().then(snapshot => {
  snapshot.docs.forEach(doc => {
    this.setState({
      location: {...doc.data()}
    })
  })
});

db.collection('hours').get().then(snapshot => {
  snapshot.docs.forEach(doc => {
    this.setState({
      hours: {...doc.data()}
    })
  })
});
}

render({
  {(this.state.hours === null)? <Footer hours={this.state.hours} location={this.state.location}/> : null }
})
Hai Pham
  • 2,188
  • 11
  • 20
0

you could just change the render code to check if the location object has key. like this

render({
  {(Object.keys(this.state.hours).length <= 0)? <Footer hours={this.state.hours} location={this.state.location}/> : null }
})
vdj4y
  • 2,649
  • 2
  • 21
  • 31