import { useState, ChangeEvent, useEffect, FormEvent } from 'react'; import axios from 'axios'; // Redux import { useDispatch, useSelector } from 'react-redux'; import { bindActionCreators } from 'redux'; import { actionCreators } from '../../../store'; import { State } from '../../../store/reducers'; // Typescript import { ApiResponse, Weather, WeatherForm } from '../../../interfaces'; // UI import { InputGroup, Button, SettingsHeadline } from '../../UI'; // Utils import { inputHandler, weatherSettingsTemplate } from '../../../utility'; export const WeatherSettings = (): JSX.Element => { const { loading, config } = useSelector((state: State) => state.config); const dispatch = useDispatch(); const { createNotification, updateConfig } = bindActionCreators( actionCreators, dispatch ); // Initial state const [formData, setFormData] = useState( weatherSettingsTemplate ); // Get config useEffect(() => { setFormData({ ...config, }); }, [loading]); // Form handler const formSubmitHandler = async (e: FormEvent) => { e.preventDefault(); // Check for api key input if ((formData.lat || formData.long) && !formData.weather_enabled) { createNotification({ title: 'Warning', message: 'You need to enable the weather module to use it', }); } // Save settings await updateConfig(formData); // Update weather axios .get>('/api/weather/update') .then(() => { createNotification({ title: 'Success', message: 'Weather updated', }); }) .catch((err) => { createNotification({ title: 'Error', message: err.response.data.error, }); }); }; // Input handler const inputChangeHandler = ( e: ChangeEvent, options?: { isNumber?: boolean; isBool?: boolean } ) => { inputHandler({ e, options, setStateHandler: setFormData, state: formData, }); }; // Get user location const getLocation = () => { window.navigator.geolocation.getCurrentPosition( ({ coords: { latitude, longitude } }) => { setFormData({ ...formData, lat: latitude, long: longitude, }); } ); }; return (
formSubmitHandler(e)}> {/* API KEY */} inputChangeHandler(e)} /> Required for weather module to work. {/* LAT */} inputChangeHandler(e, { isNumber: true })} step="any" lang="en-150" /> Click to get current location {/* LONG */} inputChangeHandler(e, { isNumber: true })} step="any" lang="en-150" /> {/* TEMPERATURE */} {/* WEATHER DATA */} ); };