0
votes

I'm currently working on a project to implement a website to check the weather forecast.

I'm trying to get the value from the input field and when I click the submit button, this value should be set to cityName. What do I have to change in order to make this work?

import { useState, useEffect } from "react"


export function WeatherInfo() {

    const token: string = '7ebe7c2a03cd48c090a193437'

    async function getCurrentWeather(cityName: string): Promise<any> {
        const response = await fetch(`http://api.weatherapi.com/v1/current.json?key=${token}&q=${cityName}`)
        const data = await response.json()
        console.log(data)
        return data
    }

    const [cityName, setCityName]: any = useState('')
    const [cityWeather, setCityWeather] = useState({})
    const [value, setValue] = useState('')

    const handleChange = (event: any) => {
        setValue(event.target.value)
    }

    const handleSubmit = (event: any) => {
        event.preventDefault()
        setCityName(value)
    }

    useEffect(() => {
        async function fetchData() {
            const cityWeather = await getCurrentWeather(cityName)

        }
        fetchData()
    })


    return (
        <div >
            <form onSubmit={handleSubmit}>
                <input onChange={handleChange} placeholder="Type here" />
                <button>Search</button>
            </form>

        </div>
    );

}
1

1 Answers

0
votes

You should add a dependency array to your effect hook so that it triggers whenever cityName changes. You should also call setCityWeather when the request completes to update that state

useEffect(() => {
  getCurrentWeather(cityName).then(setCityWeather);
}, [cityName]);