I'm encountering a problem where my api call is being fired twice instead of once and because of that it's rendering 2 charts as well. Why?
export default class Graph extends Component {
constructor(props) {
super(props);
this.state: {
humidity_data
}
axios_humidity_data = () => {
return new Promise((resolve, reject) => {
try {
axios
.get(
`url'`
)
.then(response => {
const data = response.data.results[0].series[0].values;
let date = [];
let humidity = [];
data.forEach(chart_item => {
date.push(chart_item[0]);
humidity.push(chart_item[1]);
});
this.setState({
humidity_data: {
labels: date,
datasets: [
{
label: "Humidity %",
data: humidity,
}
]
}
});
console.log(data);
resolve(data);
});
} catch (err) {
reject(err);
}
});
};
componentDidMount() {
this.axios_humidity_data();
}
render() {
return (
<div>
<Line
data={this.state.pressure_data}
options={{
title: {
display: true,
text: "Pressure kPa",
},
}}
/>
</div>
);
}
}
I'm expecting only one call to be fired and one chart to be rendered but instead it's firing twice and rendering 2 charts.
Use this Approach:
export default class Graph extends Component {
constructor(props) {
super(props);
this.state: {
humidity_data
}
var s = true;
if (s) {
axios_humidity_data = () => {
return new Promise((resolve, reject) => {
try {
axios
.get(
`url'`
)
.then(response => {
const data = response.data.results[0].series[0].values;
let date = [];
let humidity = [];
data.forEach(chart_item => {
date.push(chart_item[0]);
humidity.push(chart_item[1]);
});
this.setState({
humidity_data: {
labels: date,
datasets: [
{
label: "Humidity %",
data: humidity,
}
]
}
});
console.log(data);
resolve(data);
});
} catch (err) {
reject(err);
}
});
};
}
s = false;
componentDidMount() {
this.axios_humidity_data();
}
render() {
return (
<div>
<Line
data={this.state.pressure_data}
options={{
title: {
display: true,
text: "Pressure kPa",
},
}}
/>
</div>
);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.