import { useState, ChangeEvent, useEffect, FormEvent } from 'react'; import axios from 'axios'; // Redux import { connect } from 'react-redux'; import { createNotification, updateConfig } from '../../../store/actions'; // Typescript import { ApiResponse, Config, GlobalState, NewNotification, Weather, WeatherForm, } from '../../../interfaces'; // UI import InputGroup from '../../UI/Forms/InputGroup/InputGroup'; import Button from '../../UI/Buttons/Button/Button'; // Utils import { inputHandler, weatherSettingsTemplate } from '../../../utility'; interface ComponentProps { createNotification: (notification: NewNotification) => void; updateConfig: (formData: WeatherForm) => void; loading: boolean; config: Config; } const WeatherSettings = (props: ComponentProps): JSX.Element => { // Initial state const [formData, setFormData] = useState( weatherSettingsTemplate ); // Get config useEffect(() => { setFormData({ ...props.config, }); }, [props.loading]); // Form handler const formSubmitHandler = async (e: FormEvent) => { e.preventDefault(); // Check for api key input if ((formData.lat || formData.long) && !formData.WEATHER_API_KEY) { props.createNotification({ title: 'Warning', message: 'API key is missing. Weather Module will NOT work', }); } // Save settings await props.updateConfig(formData); // Update weather axios .get>('/api/weather/update') .then(() => { props.createNotification({ title: 'Success', message: 'Weather updated', }); }) .catch((err) => { props.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, }); }; return (
formSubmitHandler(e)}> inputChangeHandler(e)} /> Using {' '} Weather API . Key is required for weather module to work. inputChangeHandler(e, { isNumber: true })} step="any" lang="en-150" /> You can use {' '} latlong.net inputChangeHandler(e, { isNumber: true })} step="any" lang="en-150" />
); }; const mapStateToProps = (state: GlobalState) => { return { loading: state.config.loading, config: state.config.config, }; }; export default connect(mapStateToProps, { createNotification, updateConfig })( WeatherSettings );