I am currently working on a weather app using react native as a fun project. I have set up an API to fetch weather data in JSON format.
My goal is to show the hourly weather details based on the current time of the day.
export default class App extends React.Component {
constructor (props) {
super(props);
this.state = {
isLoading: true,
};
}
componentDidMount() {
const fetch = require('node-fetch');
fetch('https://api.weatherapi.com/v1/forecast.json', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
isLoading: false,
dataSource: responseJson,
})
console.log(responseJson.forecast.forecastday[0].hour[0].time.split(" ")[1]);
const time = responseJson.location.localtime.split(" ")[1];
}).catch((error) => {
console.error(error);
});
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={{flex:1, paddingTop: 20}}>
<Text style={styles.text}>{this.state.dataSource.location.name}</Text>
<Text style={styles.mainText}>{this.state.dataSource.current.condition.text}</Text>
<Text style={styles.tempText}>{this.state.dataSource.current.temp_c + '℃'}</Text>
<View style={{flex:1, flexDirection: 'row', textAlign: 'center', paddingLeft: 90}}>
<Text style={styles.maxTempText}>{'H: ' + this.state.dataSource.forecast.forecastday[0].day.maxtemp_c + '℃'}</Text>
<Text style={styles.maxTempText}>{'L: ' + this.state.dataSource.forecast.forecastday[0].day.mintemp_c + '℃'}</Text>
</View>
</View>
);
}
}
const myMainTime = () => {
const mainTime = this.state.dataSource.forecast.forecastday[0].hour[0].time.split(" ")[1];
{this.state.dataSource.forecast.forecastday[0].hour.map((item) => (
if ( mainTime >= time ) {
return (
<ScrollView horizontal={true}>
<View style={{flex:1, flexDirection: 'row', textAlign: 'center'}}>
<View>
<Text>{item.time.split(" ")[1]}</Text>
<Image source={{url: "https:" + item.condition.icon}}
style={{ width: 50, height: 50, paddingBottom: 10, alignItems: 'center', justifyContent: 'center' }}
/>
<Text>{item.temp_c + '℃'}</Text>
</View>
))}
</View>
</ScrollView>
)
}
}
Below is the provided JSON data:
{
"location": {
"name": "New York",
"region": "New York",
"country": "United States of America",
"lat": 40.71,
"lon": -74.01,
"tz_id": "America/New_York",
"localtime_epoch": 1623928876,
"localtime": "2021-06-17 7:21"
},
"current": {
...
(Please note that the rest of the JSON data has been omitted for brevity)
I want to iterate through the hourly weather data and only display the information within the app if the current time matches or exceeds the time in the JSON. Is there a way to achieve this?