import { useState, ChangeEvent, useEffect, FormEvent } from 'react'; import { connect } from 'react-redux'; import axios from 'axios'; import { ApiResponse, Config, NewNotification, Weather } from '../../../interfaces'; import InputGroup from '../../UI/Forms/InputGroup/InputGroup'; import Button from '../../UI/Buttons/Button/Button'; import { createNotification } from '../../../store/actions'; interface FormState { WEATHER_API_KEY: string; lat: number; long: number; isCelsius: number; } interface ComponentProps { createNotification: (notification: NewNotification) => void; } const WeatherSettings = (props: ComponentProps): JSX.Element => { const [formData, setFormData] = useState({ WEATHER_API_KEY: '', lat: 0, long: 0, isCelsius: 1 }) const inputChangeHandler = (e: ChangeEvent, isNumber?: boolean) => { let value: string | number = e.target.value; if (isNumber) { value = parseFloat(value); } setFormData({ ...formData, [e.target.name]: value }) } useEffect(() => { axios.get>('/api/config?keys=WEATHER_API_KEY,lat,long,isCelsius') .then(data => { let tmpFormData = { ...formData }; data.data.data.forEach((config: Config) => { let value: string | number = config.value; if (config.valueType === 'number') { value = parseFloat(value); } tmpFormData = { ...tmpFormData, [config.key]: value } }) setFormData(tmpFormData); }) .catch(err => console.log(err)); }, []); const formSubmitHandler = (e: FormEvent) => { e.preventDefault(); axios.put>('/api/config', formData) .then(() => { props.createNotification({ title: 'Success', message: 'Settings updated' }) // Update weather with new settings axios.get>('/api/weather/update') .then(() => { props.createNotification({ title: 'Success', message: 'Weather updated' }) }) .catch((err) => { props.createNotification({ title: 'Error', message: err.response.data.error }) }); }) .catch(err => console.log(err)); // set localStorage localStorage.setItem('isCelsius', JSON.stringify(parseInt(`${formData.isCelsius}`) === 1)) } return (
formSubmitHandler(e)}> inputChangeHandler(e)} /> Using {' '}Weather API inputChangeHandler(e, true)} /> You can use {' '}latlong.net inputChangeHandler(e, true)} />
) } export default connect(null, { createNotification })(WeatherSettings);