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

102 lines
2.5 KiB
TypeScript
Raw Normal View History

2021-05-19 18:26:57 +02:00
import { useState, useEffect, Fragment } from 'react';
import axios from 'axios';
// Redux
import { connect } from 'react-redux';
// Typescript
2021-10-22 13:31:02 +02:00
import { Weather, ApiResponse, GlobalState, Config } from '../../../interfaces';
2021-05-19 18:26:57 +02:00
// CSS
2021-05-19 18:26:57 +02:00
import classes from './WeatherWidget.module.css';
// UI
import WeatherIcon from '../../UI/Icons/WeatherIcon/WeatherIcon';
interface ComponentProps {
configLoading: boolean;
2021-10-22 13:31:02 +02:00
config: Config;
}
const WeatherWidget = (props: ComponentProps): JSX.Element => {
2021-05-19 18:26:57 +02:00
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(),
2021-10-22 13:31:02 +02:00
updatedAt: new Date(),
2021-05-19 18:26:57 +02:00
});
const [isLoading, setIsLoading] = useState(true);
// Initial request to get data
2021-05-19 18:26:57 +02:00
useEffect(() => {
2021-10-22 13:31:02 +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);
})
2021-10-22 13:31:02 +02:00
.catch((err) => console.log(err));
2021-05-19 18:26:57 +02:00
}, []);
// Open socket for data updates
useEffect(() => {
2021-10-22 13:31:02 +02:00
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,
2021-10-22 13:31:02 +02:00
...data,
});
};
return () => webSocketClient.close();
}, []);
2021-05-19 18:26:57 +02:00
return (
<div className={classes.WeatherWidget}>
2021-10-22 13:31:02 +02:00
{isLoading ||
props.configLoading ||
(props.config.WEATHER_API_KEY && weather.id > 0 && (
<Fragment>
<div className={classes.WeatherIcon}>
<WeatherIcon
weatherStatusCode={weather.conditionCode}
isDay={weather.isDay}
/>
</div>
<div className={classes.WeatherDetails}>
{props.config.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>
2021-10-22 13:31:02 +02:00
);
};
2021-05-19 18:26:57 +02:00
const mapStateToProps = (state: GlobalState) => {
return {
configLoading: state.config.loading,
2021-10-22 13:31:02 +02:00
config: state.config.config,
};
};
2021-10-22 13:31:02 +02:00
export default connect(mapStateToProps)(WeatherWidget);