Here is my SalesOverview1 component. I'm making an axios request after the user clicks on the Sales Overview tab. The code for the onClick handler is in the parent component where I update the state to indicate that a click has been made, I basically change the state to true. And then I conditionally render the SalesOverview1 component based on the click and then inside componentDidMount, I make the axios request. I'm not able to see the chart on the 1st click even though data is being fetched. But when I click on another tab and then click back on the Sales Overview tab, I can see it.
class SalesOverview1 extends Component {
state = {
page_id: 4,
hcp_id: 101,
sales_overview_data: []
}
componentDidMount() {
console.log('Clicked on sales Overview!');
let page_id = this.state.page_id;
let hcp_id = this.state.hcp_id;
console.log('state: ', this.state);
axios.post('/test-json', {
page_id: page_id,
hcp_id: hcp_id
})
.then((res) => {
const dataRequest = res.data;
console.log('State before loading data in sales overview: ', this.state);
console.log('received data inside sales overview', res.data);
this.setState({ ...this.state, sales_overview_data: res.data });
console.log('State after loading data in sales overview: ', this.state);
// this.props.salesOverviewDataFromParent(this.state.sales_overview_data);
this.forceUpdate();
}, (error) => {
console.log(error);
});
}
return(
<>
<div role="tabpanel" id="tablet-3" class="tab-pane" >
<div class="panel-body" style={{ backgroundColor: "rgb(243,243,244)", border: "none", margin: 0 }}>
<div class='row'>
{
this.state.sales_overview_data.length !== 0 &&
<ChartBox
data={this.state.sales_overview_data[401]}
/>
}
</div>
</div>
</div>
This component is being triggered like this in the parent Search component:
class Search{
state={
sales_overview_clicked: false
}
...
salesOverviewButtonClicked = () => {
this.setState({ ...this.state, sales_overview_clicked: true })
}
return(
<div>
<ul class="nav nav-tabs" role="tablist">
<li><a class="nav-link " data-toggle="tab" href="#tablet-3" onClick={this.salesOverviewButtonClicked}> <i class="fa fa-bar-chart-o"></i>Sales Overview</a></li>
</ul>
<div class="tab-content">
{this.state.sales_overview_clicked === true && <SalesOverview1 />}
</div>
</div>
I've kept only the relevant code and deleted the unnecessary code.
A visual of how the Sales Overview tab looks like: