Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
How can I update the setDegrees based on the city I write with React?

I'm trying to learn react.

Based on what I write in the input field, the temperature should change consequently, but I can't find which is the best method to do it.

My logic tells me to put the setDegrees under the inputChange function so when I type a new city the weather also change, but I can't do it since the data i'm trying to get aren't global.

import React, {useState, useEffect} from 'react'
import axios from 'axios';
import City from './components/City';


function App() {

  const [city, setCity] = useState("Rome")
  const [degrees, setDegrees] = useState("")

  useEffect(() => {
    
  const options = {
    url: 'https://weatherapi-com.p.rapidapi.com/current.json',
    params: {q: city},
    headers: {
      'X-RapidAPI-Host': 'weatherapi-com.p.rapidapi.com',
      'X-RapidAPI-Key': '---'
    }
  };

  axios.request(options).then(res => {
    setDegrees(res.data.current.temp_c)

   }).catch( error => console.log(error))
  },[])

  const inputChange = e => {
    setCity (e.target.value)
  }

  return (
    <div>
      <input type="text" placeholder='Type the city' onChange={inputChange}/>
      <City 
      city = {city}
      degrees = {degrees}
      />
    </div>
  )
}

export default App
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are missing a logic where you re-fetch results on city change, there are plenty ways to approach it, here is a simple example (lazy fetch):

function App() {
  const [city, setCity] = useState("Rome");
  const [degrees, setDegrees] = useState("");

  const fetchDegrees = (city) => {
    const options = {
      url: "https://weatherapi-com.p.rapidapi.com/current.json",
      params: { q: city },
      headers: {
        "X-RapidAPI-Host": "weatherapi-com.p.rapidapi.com",
        "X-RapidAPI-Key": "---",
      },
    };

    axios
      .request(options)
      .then((res) => {
        setDegrees(res.data.current.temp_c);
      })
      .catch((error) => console.log(error));
  };

  useEffect(() => {
    fetchDegrees();
  }, []);

  const inputChange = (e) => {
    setCity(e.target.value);
  };

  return (
    <div>
      <input type="text" placeholder="Type the city" onChange={inputChange} />
      <button onClick={() => fetchDegrees(city)}>Search city</button>
      <City city={city} degrees={degrees} />
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda