0

Hi guys Im building a weather app in React and I wanted to set the state variable "city" to the input value so that I can plug it back into the API URL but I had to click twice for the API to display properly. The first click returned "Error: Request failed with status code 400".

This is where I am getting the API from:

const URL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${APIKey}`;

This is my API call:

  const getCity = () => {
    axios
      .get(URL)
      .then(function (response) {
        setWeatherData(response.data);
      })
      .catch(function (err) {
        console.warn(err);
      });
  };

This is the function I was having trouble with...

  function handleChange() {
    const bar = document.getElementById("input-field").value;
    if (bar.indexOf(" ") > -1) {
      setCity(bar.split(" ").join("+"));
    } else {
      setCity(bar);
    }
  }

This is the JSX:

 <input
   id="input-field"
   className="searchbar"
   type="text"
   placeholder="Name of city (e.g. Austin"
  />
  <button
    className="searchbtn"
    onClick={() => {
      handleChange();
      getCity();
    }}
  >
    search
  </button>

0

1 Answer 1

1

The problem is that city and therefore URL are only evaluated at the next render, not immediately.

Remove getCity() from your onClick handler and add it in a useEffect() that depends on city

useEffect(() => {
  axios.get("https://api.openweathermap.org/data/2.5/weather", {
    params: {
      q: city,
      appid: APIKey
    }
  })
  .then(({ data }) => setWeatherData(data))
  .catch(console.warn)
}, [ city ])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.