All i want is that through App.js, I take input for city name and display the AQI fetched from the API in AirQuality.js. But it just isn't working correctly. Can someone please help me on this? I am new to react API.It works fine if I simply hardcode the city name.
import React from "react";
import "./App.css";
class Airquality extends React.Component {
constructor(props) {
super(props);
this.state = {
info: {},
city: {},
parameters: {},
isLoaded: false,
};
}
getAirquality = (search) => {
fetch(
"https://api.waqi.info/feed/" +
search +
"/?token=3c8f71c8438c1b6a06f60477eaf429fe2b61cd3d",
)
.then((response) => response.json())
.then((data) => {
const newInfo = data.data;
const newCity = newInfo.city;
const tempData = newInfo.iaqi;
const newParameters = tempData.pm25;
const loaded = true;
const newState = Object.assign({}, this.state, {
isLoaded: loaded,
info: newInfo,
city: newCity,
parameters: newParameters,
});
this.setState(newState);
});
};
componentDidMount() {
this.getAirquality(this.props.search);
}
render() {
this.getAirquality(this.props.search);
if (!this.state.isLoaded) {
return <div>....Loading</div>;
} else {
return (
<div className="App">
<h1>
The AQI(Air Quality Index) in{" "}
{this.state.city.name} is {this.state.info.aqi}{" "}
today.
<br />
Concentration of PM2.5 particle :{" "}
{this.state.parameters.v}
</h1>
</div>
);
}
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = { name: "" };
this.handleInput = this.handleInput.bind(this);
}
handleInput(event) {
this.setState({
name: event.target.value,
});
}
render() {
return (
<div className="App">
<form onSubmit={this.handleInput}>
<label>
Enter the city name:
<input
type="text"
onChange={this.handleInput}
/>
</label>
</form>
<Airquality search={this.state.value} />
</div>
);
}
}