- Joined
- Sep 12, 2022
- Messages
- 39
- Reaction score
- 0
Without using any state management library, I want to pass the location state from InputsAndBtn component into the fetch in the WeatherApi() so API searches can be done with the input location. Note that they are in different files but in the same folder, how do I do this as I am stuck and I do not want to move them into one file?
JSX:
import { API_KEY, BASE_URL } from "./keys";
import { useEffect, useState } from "react";
const WeatherApi = ({location}) => {
const [apiData, setApiData] = useState(null);
useEffect(() => {
fetch(`${BASE_URL}weather?q=${location}&appid=${API_KEY}`)
.then((res) => res.json())
.then((data) => {
setApiData(data);
console.log(data);
})
.catch((error) => console.log(error));
}, []);
return { apiData };
};
export default WeatherApi;
JSX:
import { useState } from "react"
import './App.css';
import WeatherApi from "./api";
const InputsAndBtn = () => {
const [location, setLocation] = useState("")
const {apiData} = WeatherApi({ location })
const [clouds, setClouds] = useState(null)
const [description, setDescription] = useState(null)
function handleChange(event) {
setLocation(event.target.value)
}
function handleClouds() {
setClouds(apiData.clouds.all)
}
function handleDescription() {
setDescription(apiData.weather[0]["description"])
}
function handleBtn(event) {
event.preventDefault()
if(location === apiData.name) {
handleClouds()
handleDescription()
}
}
return (
<form className="form">
<div style={{display: "flex"}}>
<section style={{marginRight: "auto"}}>
<input
onChange={handleChange}
type="text"
placeholder="enter a city"
value={location}
>
</input>
<button onClick={handleBtn}>Start</button>
</section>
{clouds && <section style={{backgroundColor: "red", width: "30vw", height: "100vh"}}>
<h1>{clouds}</h1>
<h2>{description}</h2>
</section>}
</div>
</form>
)
}
export default InputsAndBtn