Well I am making this weather app with the use of an api. So, first I have to show the weather of a default city. Then when I select the other cities, the component will render again to give me the weather data of selected cities. So far I have done on my project:
const initialDivisionId = "3";
const getDivision = (divisionId) => {
return divisions.find((division) => division.id === divisionId);
};
class Weather extends React.Component {
constructor(props) {
super(props);
const division = getDivision(initialDivisionId);
this.state = {
divisionId: initialDivisionId,
lat: division.lat,
long: division.long,
currentWeatherData: [],
hourlyWeatherData: [],
dailyWeatherData: []
};
}
onDivisionChange = (event) => {
const divisionId = event.target.value;
const { lat, long } = getDivision(divisionId);
this.setState({
divisionId: event.target.value,
lat: lat.lat,
long: long.long
});
};
componentDidMount() {
fetch(
`https://api.openweathermap.org/data/2.5/onecall?lat=${this.state.lat}&lon=${this.state.long}&units=metric&exclude=alerts&appid={api_key}`
)
.then((res) => res.json())
.then(
(result) => {
this.setState({
currentWeatherData: result.current,
hourlyWeatherData: result.hourly[0],
dailyWeatherData: result.daily[0]
});
},
(error) => {
console.log(error);
this.setState({
error
});
}
);
}
render() {
console.log(this.state.currentWeatherData);
console.log(this.state.hourlyWeatherData);
console.log(this.state.dailyWeatherData);
return (
<div>
<Title />
<Select
variant="filled"
w="30%"
placeholder="Select option"
value={this.state.divisionId}
onChange={this.onDivisionChange}
>
{divisions.map((division) => (
<option key={division.id} value={division.id}>
{division.name}
</option>
))}
</Select>
<div>
<Stack spacing={6}>
<Heading color="tomato" size="4xl">
{this.state.currentWeatherData.dt}
</Heading>
<Heading color="gray" size="3xl">
{this.state.currentWeatherData.temp}
</Heading>
<Heading color="blue" size="2xl">
{this.state.hourlyWeatherData.pressure}
</Heading>
<Heading color="black" size="xl">
{this.state.hourlyWeatherData.temp}
</Heading>
<Heading color="black" size="lg">
{this.state.dailyWeatherData.clouds}
</Heading>
<Heading color="yellow" size="md">
{this.state.dailyWeatherData.humidity}
</Heading>
</Stack>
</div>
</div>
);
}
}
const Title = () => {
return (
<Text align="center">
<Heading size="xl">Weather App</Heading>
</Text>
);
};
function App() {
return (
<ChakraProvider>
<Weather />
</ChakraProvider>
);
}
export default App;
So, I know I have to use shouldComponentUpdate lifecycle method if I want to re-render. How can I re-render the same component if I want to have the weather response of other cities? Or do I need to pass states as props to other component and then I have to fetch the api? Need help!