1

I've been browsing a lot of stack overflow questions about this subject, but I still don't get it... I'm trying this solution answering my problem very well : https://stackoverflow.com/a/42601915/2617419

Here is what I have :

class EnterpriseContainer extends Component {
    constructor(props) {
        super(props);
        this.state = {hit: props.hit};
    }

    async componentDidMount() {
        if (this.state.hit === undefined) {
            let h = await getObjectIDAsync();
            this.setState({hit: h});
        } else {
        }
    }

    render() {
        return (
            <Grid item xs={12} sm={12} md={12} lg={12} xl={12}>
                <Paper className="paper" elevation={1} style={{'paddingLeft': '0px'}}>

                    <Grid
                        container
                    >
                        <EnterpriseLogo image={this.state.hit.image}/>
                        <EnterpriseInfo hit={this.state.hit}/>
                    </Grid>
                </Paper>
            </Grid>
        );
    }
}

I understand that this logic is made to first load the react components, and then asynchronisly load data into it. If I simply load the hit object as a stringify object (using JSON.stringify(hit)) into my component, it works fine. But the components EnterpriseLogo and EnterpriseInfo use the hit props referencing for example props.hit.objectID, and it will make the app crash because this ref doesn't exist yet.

I think I have a design problem somewhere but I'm not sure where to go.

Community
  • 1
  • 1
romain-lavoix
  • 403
  • 2
  • 6
  • 20
  • Are you using plugin `transform-async-to-generator` and `stage-1` preset in your webpack config – Shubham Khatri May 15 '17 at 09:13
  • that's a good question, I'm using create-react-app. I see it included as `babel-plugin-transform-async-to-generator` – romain-lavoix May 15 '17 at 10:13
  • Can you do `this.setState({hit: h}, ()=> {this.state.hit});` in componentDidMount – Shubham Khatri May 15 '17 at 10:43
  • When you are initializing the `state.hit` object in the constructor, you must make sure that all the props required by the child components are existing with defaults. Otherwise, the render method will crash during the initial render itself, as the async call won't complete before the render happens. – hazardous May 15 '17 at 10:45
  • @hazardous thanks a lot it makes sense! I thought there would be something else... – romain-lavoix May 15 '17 at 21:46

1 Answers1

1

answering to myself, initializing the state.hit with all the props required by the child components solved the problem.

romain-lavoix
  • 403
  • 2
  • 6
  • 20