1

I have been trying to debug this for hours now but to no avail. I wrote this script that basically when the component loads fetch information from my Firestore database. I then log one item from the array to the console, resulting in undefined. I don't understand why it can show me the full array but not one item. And then the entire Array resulting in the full array (partial image seen below).

enter image description here

The main goal of this component is to produce a list of the items as seen in the list component but nothing is shown. My first guess is that method for getting information from the database is asynchronous, but would this matter if the state is updated? Shouldn't the app re-render?

Here is a snippet of my code, and help would be greatly appreciated!

export default class ItemScreen extends Component {

  constructor () {
    super()
    this.state = {
      items: [],
    }
  }

  componentDidMount() {
    var items = []
    firebase.firestore().collection("items").get().then(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
          items.push(doc.data());
      });
    })
    this.setState({items: items});
    console.log(items[1])
    console.log(items)
  }

  render() {
    const { items } = this.state
    return (
        <View style={styles.container}>
          <SearchBar
            lightTheme
            onChangeText={(text) => console.log(text)}
            onClearText={() => console.log("cleared")}
            placeholder='Type Here...' 
            containerStyle={{width: "100%"}}
          />
          <List containerStyle={{width: "100%"}}>
            {
              items.map((l) => (
                <ListItem
                  roundAvatar
                  avatar={{uri:l.image}}
                  key={l.name}
                  title={l.name}
                />
              ))
            }
          </List>
        </View>
    );
  }
}
2
  • You have a promise .get().then(, remember in JS you dont have I/O blocking thats mean async execution code when you use promises, only put the logs into closure sent to then Commented Sep 21, 2018 at 1:12
  • When IO tried something like this I got an error that this.state is not a function. See below Commented Sep 21, 2018 at 1:19

1 Answer 1

4

Try restructuring to something more like

var items = []
var self = this;
firebase.firestore().collection("items").get().then(function(querySnapshot) {
  querySnapshot.forEach(function(doc) {
      items.push(doc.data());
  });
  self.setState({items: items});
  console.log(items[1])
  console.log(items)
})

The code at the bottom of your original method would run before the results are available.

Sign up to request clarification or add additional context in comments.

3 Comments

When using that structure instead I get the following error: Possible Unhandled Promise Rejection (id: 0): TypeError: this.setState is not a function
Try my updated code... the closure was messing up the scope of "this".
@kip haha so true!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.