I am trying to get weather data from an api, when fetch the data without using interpolation fetch(https://weatherapi-com.p.rapidapi.com/forecast.json?q=London&days=3
) it works fine. But when I use the code below and press enter after searching a new city I get the error message "Bad request" Parameter q is missing. Any help would be appreciated! Let me know if I can help clarify in any way.
import React from "react"
// import WeatherDisplay from "./WeatherDisplay";
import { useState, useEffect } from "react"
import { scryRenderedComponentsWithType } from "react-dom/test-utils";
import Item from "./Item"
function SearchBar() {
const [ defaultWeather, setDefaultWeather ] = useState([])
const [ searchedCity, setSearchedCity ] = useState('London')
const [ isLoaded, setIsLoaded ] = useState(false)
const [didMount, setDidMount] = useState(false);
const [ input, setInput ] = useState('')
const searchWeather = () => {
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Host': 'weatherapi-com.p.rapidapi.com',
'X-RapidAPI-Key': 'de51889a1fmshe095099b1a97993p13134fjsnc818ad7373cb'
}
};
fetch(`https://weatherapi-com.p.rapidapi.com/forecast.json?q=${searchedCity}&days=3`, options)
.then(response => response.json())
.then((data) => {
console.log(data)
setDefaultWeather(data)
setIsLoaded(true)
})
.catch(err => console.error(err));
}
useEffect(() => {
searchWeather()
}, [searchedCity])
function handleSubmit(e) {
e.preventDefault()
setSearchedCity(input)
}
if (!isLoaded) return <h3>Loading...</h3>;
return (
<div>
<form
className="search-form"
onSubmit={handleSubmit}
>
<label>Search</label>
<input
text="text"
id="search"
onChange={e => setSearchedCity(e.target.value)}
/>
{/* <button>Submit</button> */}
<div className="display">
</div>
</form>
</div>
)
}
export default SearchBar;
CodePudding user response:
I don't understand why you are setting setSearchedCity in both submit and on change but In your useEffect,At least you could add conditional as:
useEffect(() => {
if (searchedCity) searchWeather()
}, [SearchedCity])
CodePudding user response:
onChange={(e) => setInput(e.target.value)} instead of onChange={e => setSearchedCity(e.target.value)}