2021-05-19 18:26:57 +02:00
|
|
|
import { useState, useEffect, Fragment } from 'react';
|
|
|
|
import { Weather, ApiResponse } from '../../../interfaces';
|
|
|
|
import axios from 'axios';
|
|
|
|
|
|
|
|
import WeatherIcon from '../../UI/Icons/WeatherIcon/WeatherIcon';
|
|
|
|
|
|
|
|
import classes from './WeatherWidget.module.css';
|
|
|
|
|
|
|
|
const WeatherWidget = (): JSX.Element => {
|
|
|
|
const [weather, setWeather] = useState<Weather>({
|
|
|
|
externalLastUpdate: '',
|
|
|
|
tempC: 0,
|
|
|
|
tempF: 0,
|
|
|
|
isDay: 1,
|
|
|
|
conditionText: '',
|
|
|
|
conditionCode: 1000,
|
2021-06-01 14:54:47 +02:00
|
|
|
id: -1,
|
2021-05-19 18:26:57 +02:00
|
|
|
createdAt: new Date(),
|
|
|
|
updatedAt: new Date()
|
|
|
|
});
|
|
|
|
const [isLoading, setIsLoading] = useState(true);
|
|
|
|
|
2021-06-01 14:54:47 +02:00
|
|
|
// Initial request to get data
|
2021-05-19 18:26:57 +02:00
|
|
|
useEffect(() => {
|
|
|
|
axios.get<ApiResponse<Weather[]>>('/api/weather')
|
|
|
|
.then(data => {
|
2021-06-01 14:54:47 +02:00
|
|
|
const weatherData = data.data.data[0];
|
|
|
|
if (weatherData) {
|
|
|
|
setWeather(weatherData);
|
|
|
|
}
|
2021-05-19 18:26:57 +02:00
|
|
|
setIsLoading(false);
|
|
|
|
})
|
|
|
|
.catch(err => console.log(err));
|
|
|
|
}, []);
|
|
|
|
|
2021-06-01 14:54:47 +02:00
|
|
|
// Open socket for data updates
|
|
|
|
useEffect(() => {
|
|
|
|
const webSocketClient = new WebSocket('ws://localhost:5005');
|
|
|
|
|
|
|
|
webSocketClient.onopen = () => {
|
|
|
|
console.log('WebSocket opened');
|
|
|
|
}
|
|
|
|
|
|
|
|
webSocketClient.onclose = () => {
|
|
|
|
console.log('WebSocket closed')
|
|
|
|
}
|
|
|
|
|
|
|
|
webSocketClient.onmessage = (e) => {
|
|
|
|
const data = JSON.parse(e.data);
|
|
|
|
setWeather({
|
|
|
|
...weather,
|
|
|
|
...data
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
return () => webSocketClient.close();
|
|
|
|
}, []);
|
|
|
|
|
2021-05-19 18:26:57 +02:00
|
|
|
return (
|
|
|
|
<div className={classes.WeatherWidget}>
|
|
|
|
{isLoading
|
|
|
|
? 'loading'
|
2021-06-01 14:54:47 +02:00
|
|
|
: (weather.id > 0 &&
|
|
|
|
(<Fragment>
|
|
|
|
<div className={classes.WeatherIcon}>
|
|
|
|
<WeatherIcon
|
|
|
|
weatherStatusCode={weather.conditionCode}
|
|
|
|
isDay={weather.isDay}
|
|
|
|
/>
|
|
|
|
</div>
|
|
|
|
<div className={classes.WeatherDetails}>
|
|
|
|
<span>{weather.tempC}°C</span>
|
|
|
|
<span>{weather.conditionCode}</span>
|
|
|
|
</div>
|
|
|
|
</Fragment>)
|
2021-05-19 18:26:57 +02:00
|
|
|
)
|
|
|
|
}
|
|
|
|
</div>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
export default WeatherWidget;
|