A
A
Alex102142020-01-31 12:20:15
React
Alex10214, 2020-01-31 12:20:15

How to properly process the data?

There is this code:

import React, { Component } from 'react';
import AllPositionData from "./DataPosition/AllPositionData";
import ErrorMassage from './GlobalCont/ErrorMassage';
import GlobalCont from './GlobalCont/GlobalCont';

export default class App extends Component {
    AllPositionData = new AllPositionData();
    state = {
        pos: {},
        peoples: {},
        error: true
    }

    componentDidMount() {
        this.updataPos()
        this.updataPeoples()
        // setInterval(() => this.updata(), 5000);  
    }

    updataPos() {
        this.AllPositionData.getResourcePos()
            .then(this.onDataLoadedPos)
            .catch(this.onError);
    }
    updataPeoples() {
        this.AllPositionData.getResourcePeoples()
            .then(this.onDataLoadedPeoples)
            .catch(this.onError);
    }

    onDataLoadedPos = (pos) => {
        this.setState({
            pos,
            error: false
        });
    }

    onDataLoadedPeoples = (peoples) => {
        this.setState({
            peoples,
            error: false
        });
    }

    onError = () => {
        this.setState({
            error: true
        })
    }

    render() {

        const { error } = this.state;

        if (error) {
            return <ErrorMassage />
        }

        return (
            <GlobalCont datapos={this.state} />
        )
    }
}


In it, the data is obtained after loading the component. To do this, I use componentDidMount () And it turns out that in the console I first have an empty object, and then an object with data. The question is how to remove an empty object? So that an object with data comes once and not empty, but already with data?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
abberati, 2020-01-31
@Alex10214

No way. Asynchrony. The data you are trying to render is not yet available. All you can do is check if the data has loaded, and if it hasn't loaded yet, don't try to access it. Render a spinner.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question