Alexander Beletsky
Alexander Beletsky

Reputation: 19821

React/Redux Loading application state in component constructor

I'm rendering high-order component, say Application and I need to fetch some data from server, before it's rendered. What I do, in constructor of Application I issue loadApplicationState() action, that performs server call and prepares initial state.

Some simplified code,

class Application extends Component {
  constructor(props) {
    super(props);
    const { dispatch } = this.props;

    dispatch(loadApplicationState());
  }

  render() {
    const { stateLoaded } = this.props.state;

    render (
      <div>
        { stateLoaded ? renderApp() : renderProgress() }
      </div>
    )
  }
}

function loadApplicationState() {
  return (dispatch) => {
    // fetch data and once ready,
    applicationStateLoaded(data);
  }
}

I've tried that on practice, it works fine. But not sure is this a right approach? Especially using a constructor for such purposes.

Upvotes: 5

Views: 5725

Answers (1)

Steven
Steven

Reputation: 1596

We run this in componentDidMount, and then test for an $isLoading flag in our Redux state, rendering either a loading indicator or the actual UI. Something like so:

import React, { Component } from 'react';

const mapStateToProps = (state) => ({
  $isLoading: state.initialState.$isLoading
})
const mapDispatchToProps = (dispatch) => ({
  loadApplicationState(){ dispatch(loadApplicationState()); }
})

export class Application extends Component {
  componentDidMount(){
    this.props.loadApplicationState();
  }

  render(){
    const {
      $isLoading
    } = this.props;

    {$isLoading ? (<Loader />) : <ActualApplication />}
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Application)

Upvotes: 6

Related Questions