I'm very new to React and programming in general so bear with me. I'm working through a tutorial where you fetch data from the Open Weather API and display it. What I don't like is there are two input fields (city) & (country) and I would like to use one input field (city, country) to fetch the data. There might be an API for this on open weather, but I'd like to learn for future situations. After trying a variety of lost attempts and google searches, I've made no progress. Bonus points if you can also error handle and "unhandled error" when text can't be found via the API call (entering a state in the country field)
App.js
import React, {useState} from 'react';
import Form2 from './Form2'
import Weather from './Weather'
import './App.css'
export default function App() {
const [weather,setWeather] = useState([])
const APIKEY = 'myKey'
async function fetchData(e) {
const city = e.target.elements.city.value
const country = e.target.elements.country.value
e.preventDefault()
const apiData = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city},${country}&APPID=${APIKEY}`)
.then( res => res.json())
.then(data => data)
if(city && country && city !== undefined && country !== undefined) {
setWeather({
data: apiData,
city: apiData.city,
country: apiData.sys.country,
description: apiData.weather[0].description,
temperature: Math.round(apiData.main.temp * 9/5 - 459.67),
error:""
}
)} else {
setWeather({
data: '',
city: '',
country: '',
description: '',
temperature: '',
error:"Please Type A City And Country"
}
)}
}
return (
<div className="App">
<h3>WEATHER APP</h3>
<Form2 getWeather={fetchData} />
<Weather
city={weather.city}
country={weather.country}
description={weather.description}
temperature={weather.temperature}
error={weather.error}
/>
{console.log(weather.data)}
</div>
);
}
Form.jsx
import React from 'react'
const Form2 = (props) => {
return (
<form onSubmit={props.getWeather}>
<input
type='text'
placeholder='city'
name='city'
/>
<input
type='text'
placeholder='country'
name='country'
/>
<button>Submit</button>
</form>
)
}
export default Form2;
Weather.jsx
import React from 'react'
const Weather = ({description, location, error, temperature}) => {
return (
<div>
{location && <p>{location}</p>}
{temperature && <p>{temperature} °F</p>}
{description && <p>Conditions: {description}</p>}
{error && <p>{error}</p>}
</div>
)
}
export default Weather;