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

147
Views
React onChange event fires empty string on first input

Problem - There is no string output the very first time I type in text. This is causing the last character of whatever I enter into the output to not appear. Why is this?

Some state - Focusing on name property

const [options, setOptions] = useState({
    name: '',
    signOff: ''
});

Input

<input
 type="text"
 placeholder="Enter first name"
 name="name"
 id="name"
 onChange={(e) => handleNameChange(e.target.value)}
/>

Function to fire after input change

const handleNameChange = (name: string) => {
    setOptions({
        ...options,
        name
    });
    console.log(options);
};

Example console output after typing "hello" - Why the empty string for name property?

{name: '', signOff: ''}       options.tsx:17 
{name: 'h', signOff: ''}      options.tsx:17 
{name: 'he', signOff: ''}     options.tsx:17 
{name: 'hel', signOff: ''}    options.tsx:17 
{name: 'hell', signOff: ''}   options.tsx:17 
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Its expected behaviour, because setStates are asynchronous, so when you log the state variable immediately after its being set, it logs previous value, not the updated one
If you just want to log the state changes, move console.log() to useEffect hook

const handleNameChange = (name: string) => {
    setOptions({
        ...options,
        name
    });
    console.log(options);
};
useEffect(() => {
  console.log(options);
}, [options]); 
about 4 years ago · Juan Pablo Isaza Report

0

You can add options variable as the second parameter to useEffect. This means that in every state change of this variable this function will be fired.

useEffect(() => {
  console.log(options);
}, [options]); 
about 4 years ago · Juan Pablo Isaza Report

0

This is how I do it and I haven't encountered any such problem. You can also use the same function for every other input, not just name.

<input
 type="text"
 placeholder="Enter first name"
 name="name"
 id="name"
 onChange={handleChange}
/>

const handleChange = (e) => {
    setOptions({
        ...options,
        [e.target.name]: e.target.value
    });
};
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!