Reputation: 4481
I'm developing a small react application that consist of a chart component and some other components. The chart component is a separate file/component/child component.When i click the button in the main container it calls a promise (using axio) and it returns some data as response. This response data is set as states and that state is passed to the chart component as props.But the chart doesn't load. This is because the chart has already being loaded, since the initial states where empty the chart is also empty. Is there any way of rendering the chart component only after the promise returns data?
this is my code
the button click event
ClickMe = () =>{
axios.get('http://xyzsdsd.com/abc')
.then((response)=>{
this.setState({
tags:response.data
});
console.log(this.state.tags);
}).catch((err)=>{
console.log(err);
});
}
the render function
render(){
return(
<div>
<otherComponents/>
<chart data={this.state.tags}/>
</div>
);
}
Upvotes: 0
Views: 6640
Reputation: 6882
for good UX you might want to think about the different states and flows that your component or piece of the UI might encounter.
So from the top of the head I would have 3 states. Empty slate
, loading
(since your reaching out to the server this could also take some time) and chart with data
.
So depending on the state you might want to display different components.
I would set the InitialState for in ES6 via constructor or without ES6 in the getInitialState function.
If you want to kick of the ajax onLoad
of the component axios.get
you should think about placing the componentDidMount
.
This could also work with the React-Router. So whenever you navigate to the ChartComponent it loads when it gets mounted.
If you happen to recognize that your if statements in your render function get to complicated because you business logic demands for more. You should definitely check out Redux (http://redux.js.org/)in combination with React to have better control of state and data flow.
Really great insides how to structure react apps with redux could be found in this free video series. https://egghead.io/courses/getting-started-with-redux https://egghead.io/courses/building-react-applications-with-idiomatic-redux
Hope that helps.
Upvotes: 1
Reputation: 5927
Add a condition in your render, to only render the chart component when your state.tags object is valid. On initial render, chart will not be rendered. When your AJAX call returns and setState() is called, render() will be called again with a non-null state.tags and thus render your chart.
render(){
let chart;
if (this.state.tags) {
chart = <chart data={this.state.tags}/>;
}
return (
<div>
<otherComponents/>
{chart}
</div>
);
}
Upvotes: 3