2

I have this component in react that get todo from firebase, build an array and set a state, but when I render the component I only can see the elements the first time, if I reload the page the state seems to be empty.

import React, { PureComponent } from 'react';
import firebase from 'firebase'

class Charts extends PureComponent {
    constructor(props) {
        super(props);
        this.state = { data: [] };
        this.todoRef = firebase.database().ref('Todo');
    }

    componentDidMount = () => {
        var data = [];
        this.todoRef.on('value', (snapshot) => {
            const todos = snapshot.val();
            for (let id in todos) {
                data.push({ id, ...todos[id] });
            }
        });

        this.setState({ data: data })
    }

    render() {
        return <div>
            {this.state.data.map(item => (
                <p>{item.name}</p>
            ))}
        </div>
    }
}

export default Charts;

If I use console log I get an array(0) with elements inside. I have tried locating the setState in different life cicles methods but don't seems to work.

0

1 Answer 1

1

Issue

You are calling this.setState outside the snapshot handler, so you are only passing the empty ([]) data array to the state updater.

Solution

You should move the state update into the function processing the snapshot.

componentDidMount = () => {
  const data = [];
  this.todoRef.on('value', (snapshot) => {
    const todos = snapshot.val();
    for (let id in todos) {
      data.push({ id, ...todos[id] });
    }
    this.setState({ data });
  });
}
Sign up to request clarification or add additional context in comments.

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.