O
O
One_null2019-05-07 14:37:59
JavaScript
One_null, 2019-05-07 14:37:59

What is the problem with accessing a specific array element?

In general, the problem is as follows, there is a database on firebase, there is a React component. I get data from the database and form an array of objects of the form from them:
5cd16b7761864305480657.png,
after that I try to transfer data from this array to the component state, but there is no data in the array.

class CalendarDay extends Component{
    constructor(props){
        // console.log(db);
        super(props);
        this.state = {
            production: db.map( x => (x.data === this.props.date && localStorage.user === x.user_id) ? x.production : 0),
        }
    }

My idea is simple, if the date and the current user and from the database match, output the value to the state. However, if you execute console.log(db) - the array will be displayed, it will contain values, but if you display, for example, the first object of the array console.log(db[0]) - it will be undefined. If I understand correctly, then at the moment the component is rendered, the array is not yet filled, how can this be fixed?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2019-05-07
@One_null

You can use the componentDidMount lifecycle method:

class CalendarDay extends Component {
  state = { data: [] };

  comonentDidMount() {
    // тут делаем запрос к БД и передаем данные в состояние
  }
  // ...
}

The console displays the array as of the current moment. At the time the constructor is called, the data is not there yet. To verify this, it is enough to change the call to:
console.log(JSON.stringify(db));

K
kova1ev, 2019-05-07
@kova1ev

As I understand it, getting data from the database is asynchronous. I would do this:
in the constructor I would add componentDidMount () where I would call the function for obtaining data from the database, passing it this.setState as a callback, that is, the component is mounted, the data is loaded, when the data is loaded, setState is called, the component is redrawn. While the data is not received, you can twist some preloader thread.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question