Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
onChange not working on the first input into the text field

onChange event doesn't return the first change of the text input but works on subsequent changes. Sorry if this is obvious, I'm new to React.

import React, { useState } from 'react';
import axios from 'axios'; 

function Header() {

    const [text, setText] = useState("");
    const [location, setLocation] = useState("");

    function handleChange(event) {
        setText(event.target.value);
    }

    // when submit button clicked, current state of the text input is stored inside location constant 
    function handleClick() {
        setLocation(text);
        const geoCoderURL = "http://api.openweathermap.org/geo/1.0/direct?q=" + location + "&limit=5&appid={apikey}"
        function getCoordinates(url) {
            axios.get(url).then((response) => {
                const locationLat = response.data[0].lat;
                const locationLon = response.data[0].lon;
                
            });
        } 
        getCoordinates(geoCoderURL);        
    }
    return (
        <div>
            <h1>Five Day Forecast</h1> 
            <input onChange={handleChange} type="text" name="name"autoFocus placeholder="Enter location here."/>
            <button type="submit" onClick={handleClick}>Forecast</button> 
        </div>
    )
}

export default Header;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

When you call setLocation(text);, handleClick will finish execution before the location value is actually updated.

There is no need for location and setLocation; looks like maybe location is supposed to be the same as text.

function handleClick() {
    const geoCoderURL = "http://api.openweathermap.org/geo/1.0/direct?q=" + text + "&limit=5&appid={apikey}"
    function getCoordinates(url) {
        axios.get(url).then((response) => {
            const locationLat = response.data[0].lat;
            const locationLon = response.data[0].lon;  
        });
    } 
    getCoordinates(geoCoderURL);        
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!