skip to Main Content

I am building a weather app with two components .I was testing whether the api is working but once i start to write on the input form the city name it won’t take more than one letter and again refreshes the form. Please help me I’m new to js and react.

Here’s my code :-


import axios from "axios";
import { useState } from "react";
import "./App.css";
import CityComponent from "./CityComponent";
import WeatherComponent from "./WeatherComponent";
import styled from "styled-components";
const API_KEY = "42d13a711450b30b23cab2b8a7b34e7c";`

//App file
function App() {
  const [city, updateCity] = useState();
  const [weather, updateWeather] = useState();
  const fetchWeather = async () => {

    const response = await axios.get(
      "https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}"
    );
    updateWeather(response.data);
  };


  return (
    <Container>
      <AppLabel>weather app</AppLabel>
{weather ? (

<WeatherComponent/>
) : (


      <CityComponent updateCity={updateCity} fetchWeather={fetchWeather} />
)}
    </Container>
  );
}

export default App

//citycomponent :-

<img src="/icons/perfect-day.svg" alt="#" className="Perfectday" />
      <ChooseCityLabel>Find Weather of your city</ChooseCityLabel>
      <SearchBox onSubmit={fetchWeather}>
        <input 
        placeholder="City" onChange={(e)=> updateCity(e.target.value)}/>
        <button type={"submit"}>Search</button>
      </SearchBox>

2

Answers


  1. I’m not sure but try to add the actual value to your input, also add a default value to your state :

    function CityComponent() {
      const [value, setValue] = useState('');
      ...
      return <input type="text" value={value} onChange={(e) => setValue(e.target.value)} />
    }
    

    I hope it’s gonna help..

    Login or Signup to reply.
  2.  const fetchWeather = async (e) => {
         e.preventDefault()
           console.log(city)
          const response = await axios.get(
            "https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}"
          );
          updateWeather(response.data);
        };
      
      <form onSubmit={fetchWeather}>
              <input 
              placeholder="City" value={city} onChange={(e)=> 
              updateCity(e.target.value)}/>
              <button type={"submit"}>Search</button>
            </form>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search