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 Answers 2

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 };
        }),
    ],
  });
});
Sign up to request clarification or add additional context in comments.

Comments

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 })

Comments

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.