Home > front end >  Change useState Value everytime I enter Somthing in my Input
Change useState Value everytime I enter Somthing in my Input

Time:12-11

This is the code i am working on

So, every time i make change to my input i want state to change which will change my url

but every time that happen it shows an error

Is there a alternative for onKeyPress beacuse it's not working and what change should i do to make that happen

"please read this code and tell me how to console log the JSON of my URL"

import React,{useState} from 'react';
    import './App.css';
    import axios from 'axios';
    import Nav from "./components/Nav.js"

function App() {

  const {data,setData} = useState({})
  const {city,setCity} = useState('')

  const url = `http://api.weatherapi.com/v1/current.json?key=e893692528f845dfad844704220412&q=${city}&aqi=yes`


  function searchCity(event){
    if(event.key === 'Enter') {
      axios.get(url).then((response) => {
      setData(response.data)
      console.log(response.data)
    })
    }
  }






  return (
    <div >
      <Nav />
      <div className='form'>
            <input
            value={city}
            onChange={event => setCity(event.target.value)}
            onKeyPress = {searchCity}
            placeholder='Enter City'
            type="text"
            />
            

</div>
                  <div className="Container">
        <img src="./Img/top-japan-5.jpg" alt="Japan-as-weatherapp-top" className="main-img"/>

          
            
            <div  className="Temprature">12</div>
            <div  className="Location">Japan</div>
            <div  className="Weather">cloudy</div>
            <div  className="Humidity">Humidity</div>
            <div className="line"></div>
            <div  className="Wind">Wind</div>
            
            
          


        </div>
    </div>
  );
}

export default App;

the error massage

Uncaught TypeError: city is undefined
    handleChange App.js:25
    React 23
    js index.js:5
    factory react refresh:6
    Webpack 3

CodePudding user response:

useState should use [] not {}

const [data,setData] = useState({})
const [city,setCity] = useState('')

wrap the url around useMemo

const url = useMemo(() => `http://api.weatherapi.com/v1/current.json?key=e893692528f845dfad844704220412&q=${city}&aqi=yes`, [city])

CodePudding user response:

I think it would be better to call api in onChange and use event.target.value directly not setting state for it,

something like this :

  function searchCity(cityToSearch) {
    axios
      .get(
        `http://api.weatherapi.com/v1/current.json?key=e893692528f845dfad844704220412&q=${cityToSearch}&aqi=yes`
      )
      .then(response => {
        setData(response.data);
        console.log(response.data);
      });
  }

and in input :

<input
        value={city}
        onChange={event => {
          setCity(event.target.value);
          if (event.key === 'Enter') {
            searchCity(event.target.value);
          }
        }}
        placeholder="Enter City"
        type="text"
      />

CodePudding user response:

Just off the first glimpse. Your useState is incorrect.

you have

const {data,setData} = useState({})
const {city,setCity} = useState('')

but you need

const [data, setData] = useState({});
const [city, setCity] = useState('');

Also, instead of onKeyPress on the input, I would use onSubmit on a form.

Do this...

import React, { useState } from 'react';
import './App.css';
import axios from 'axios';
import Nav from "./components/Nav.js"

function App() {
  const [data, setData] = useState({})
  const [city, setCity] = useState('')

  function searchCity(event) {
    event.preventDefault();
    const url = `http://api.weatherapi.com/v1/current.json?key=e893692528f845dfad844704220412&q=${city}&aqi=yes`;
    axios.get(url).then((response) => {
        setData(response.data)
        console.log(response.data)
    })
  }

  return (
      <div>
        <Nav />
        <form onSubmit={searchCity} className='form'>
          <input
            value={city}
            onChange={event => setCity(event.target.value)}
            placeholder='Enter City'
            type="text"
          />
        </form>
        <div className="Container">
          <img src="./Img/top-japan-5.jpg" alt="Japan-as-weatherapp-top" className="main-img"/>

          <div  className="Temprature">12</div>
          <div  className="Location">Japan</div>
          <div  className="Weather">cloudy</div>
          <div  className="Humidity">Humidity</div>
          <div className="line"></div>
          <div  className="Wind">Wind</div>
        </div>
    </div>
  );
}

export default App;
  • Related