I am new to React and was creating an app by using Open Weather Map API and when a user types in location and clicks a Find button then JSON file is gotten and properly rendered on UI. But the problem is when a user gets data about a certain location then if they type in another location then UI remains the same with the rendered data of the first location. Here is the code I am using:
import React, { Fragment, Component } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import SearchBox from "./Containers/SearchBox/SearchBox";
import Header from "./Components/Header/Header";
import styles from "./App.module.css";
import CardContainer from "./Containers/CardContainer/CardContainer";
import axios from "axios";
class App extends Component {
state = {
title: []
};
getTitle(title) {
axios
.get(
`http://api.openweathermap.org/data/2.5/forecast?q=${title}&APPID=7ad09d078633b652ecef8587a337639e&units=metric`
)
.then(res => {
this.setState(prevState => ({
title: [...prevState.title, res.data.city.name]
}));
this.setState(prevState => ({
title: [...prevState.title, res.data.list]
}));
});
}
render() {
return (
<div className="App">
<Fragment>
<Header title={"Weather App"} />
<div className="container">
<SearchBox getRequest={this.getTitle.bind(this)} />
</div>
<h1 className={styles.cityWeather}>{this.state.title[0]}</h1>
<CardContainer weatherData={this.state.title[1]} />
</Fragment>
</div>
);
}
}
export default App;
import React, { Component } from "react";
import styles from "./SearchBox.module.css";
class SearchBox extends Component {
state = { title: "" };
change(e) {
this.setState({ title: e.target.value });
}
submit(e) {
e.preventDefault();
this.props.getRequest(this.state.title);
}
render() {
return (
<form
onSubmit={this.submit.bind(this)}
className={styles.form}
action="/"
method="get"
>
<input
onChange={this.change.bind(this)}
className="form-control"
placeholder="Enter your location"
type="text"
value={this.state.title}
name="city"
id=""
/>
<div className={styles.buttonWrap}>
<button className={`btn btn-primary ${styles.button}`} type="submit">
Find
</button>
</div>
</form>
);
}
}
export default SearchBox;