1
0
Fork 0
mirror of https://github.com/pawelmalak/flame.git synced 2025-07-19 19:49:37 +02:00
flame/client/src/components/Widgets/WeatherWidget/WeatherWidget.tsx

94 lines
2.6 KiB
TypeScript
Raw Normal View History

2021-05-19 18:26:57 +02:00
import { useState, useEffect, Fragment } from 'react';
import { Weather, ApiResponse, Config } from '../../../interfaces';
2021-05-19 18:26:57 +02:00
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,
cloud: 0,
2021-05-19 18:26:57 +02:00
conditionText: '',
conditionCode: 1000,
id: -1,
2021-05-19 18:26:57 +02:00
createdAt: new Date(),
updatedAt: new Date()
});
const [isLoading, setIsLoading] = useState(true);
const [isCelsius, setIsCelsius] = useState(true);
2021-05-19 18:26:57 +02:00
// Initial request to get data
2021-05-19 18:26:57 +02:00
useEffect(() => {
// get weather
2021-05-19 18:26:57 +02:00
axios.get<ApiResponse<Weather[]>>('/api/weather')
.then(data => {
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));
// get config
if (!localStorage.isCelsius) {
axios.get<ApiResponse<Config>>('/api/config/isCelsius')
.then((data) => {
setIsCelsius(parseInt(data.data.data.value) === 1);
localStorage.setItem('isCelsius', JSON.stringify(isCelsius));
})
.catch((err) => console.log(err));
} else {
setIsCelsius(JSON.parse(localStorage.isCelsius));
}
2021-05-19 18:26:57 +02:00
}, []);
// Open socket for data updates
useEffect(() => {
const socketProtocol = document.location.protocol === 'http:' ? 'ws:' : 'wss:';
const socketAddress = `${socketProtocol}//${window.location.host}/socket`;
const webSocketClient = new WebSocket(socketAddress);
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'
: (weather.id > 0 &&
(<Fragment>
<div className={classes.WeatherIcon}>
<WeatherIcon
weatherStatusCode={weather.conditionCode}
isDay={weather.isDay}
/>
</div>
<div className={classes.WeatherDetails}>
{isCelsius
? <span>{weather.tempC}°C</span>
: <span>{weather.tempF}°F</span>
}
<span>{weather.cloud}%</span>
</div>
</Fragment>)
2021-05-19 18:26:57 +02:00
)
}
</div>
)
}
export default WeatherWidget;