#StackBounty: #reactjs Standard way of fetching external data before showing webpage (2021 September)

Bounty: 100

I like the way in AngularJS of fetching external data before showing webpage. The data will be sent one by one to the frontend before showing the webpage. We are certain that the website and the data on it is good when we see it.

$stateProvider
    .state('kpi', {
        url:'/kpi',
        templateUrl: '/htmls/kpi.html',
        resolve: {
            getUser: ['lazy', 'auth', function (lazy, auth) { return auth.getUser() }],
            postPromise: ['posts', 'getUser', function (posts, getUser) { return posts.getAll() }],
            userPromise: ['users', 'postPromise', function (users, postPromise) { return users.getAll() }],
            logs: ['kpiService', 'userPromise', function (kpiService, userPromise) { return kpiService.getLogs() }],
            subscribers: ['kpiService', 'logs', function (kpiService, logs) { return kpiService.getSubscribers() }]
        },
        controller: 'KpiCtrl'
    })

Now, I would like to achieve this in ReactJS, I tried:

class Kpi extends React.Component {
    state = { logs: [] };

    getChartOptions1 () {
       // this.state.logs is used
    }

    componentDidMount() {
        axios.get(`${BACKEND_URL}/httpOnly/kpi/logs`).then(
            logs => {
              this.setState({logs.data});
            });
    };

    render() {
        return 
            <div>
                <HighchartsReact highcharts={Highcharts} options={this.getChartOptions1()} {...this.props} />
                <div>{JSON.stringify(this.state.logs)}</div>
            </div>
    }
}

But it seems that, it first called getChartOptions1 with unready data, rendered the webpage, then fetched the external data, then called again getChartOptions1 with ready data, rendered the webpage again.

I don’t like the fact that getChartOptions was called twice (first with unready data), and the page was rendered twice.

There are several ways discussed: Hooks, React.Suspense, React.Lazy, etc. Does anyone know what’s the standard way of fetching external data before showing the webpage in React?


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.