0

I have a react app that pulls data from firebase. It adds data to the array fine. But cannot be accessed. calling the index returns undefined and length of array is 0. but when you print the array the console shows there is an element inside. Whats going on?

componentWillMount() {

    itemsRef.on('value', (snapshot) => {
        let items = snapshot.val();

        let keys = Object.keys(items);

        for(var i = 0; i < keys.length; i += 1) {
            let k = keys[i];
            let name = items[k].name;
            let start = items[k].start;

            this.state.timers.push( {
                name: name,
                start: start
            } );


        }

    });

    console.log(this.state.timers); // shows an array with stuff in it
    this.setState({timers: this.state.timers}); // timers dont get added
    // you cant even access elements in the array.
    // ex: this.state.timers[0] returns undefined, but the console shows that it exists when the whole array is printed.
}

2 Answers2

1

You shouldn't push directly to the state. Instead you should to something like this:

ES6 variant

const timers = [...this.state.timers];
timers.push({ name, start });
this.setState({ timers })
Nylsoo
  • 159
  • 1
  • 2
  • 11
1

You shouldn't mutate directly your state like you do in the `this.state.timers.push({})``

You should do something like that:

itemsRef.on('value', (snapshot) => {
  const items = snapshot.val();
  this.setState({
    timers: [
      ...this.state.timers,
      ...Object
        .keys(items)
        .map(key => {
          const { name, start } = items[key];
          return { name, start };
        }),
    ],
  });
});
yuantonito
  • 1,274
  • 8
  • 17