Home > Software engineering >  When I read a value from an input tag in React, the last typed character is not read
When I read a value from an input tag in React, the last typed character is not read

Time:01-05

I am trying to read a value from a JSX tag, using the onChange event.

When a string value is typed in the input field, I would like to store the current string in the variable enteredFlight, and I am using the useState hook to accomplish that.

Please see my code below:

import './SearchFlights.css';
import { useState } from 'react';

const SearchFlights = (props) => {
  const [enteredFlight, setEnteredFlight] = useState('');

  const flightInputHandler = (event) => {
    setEnteredFlight(event.target.value);
    console.log(enteredFlight);
    props.flightInput(enteredFlight);
  };

  return (
    <>
      <div className="container">
        <h1>Search Flights</h1>
        <form>
          <label>Enter a flight number</label>
          <input
            type="text"
            onChange={flightInputHandler}
          />
        </form>
      </div>
    </>
  );
};
export default SearchFlights;

However, I have noticed that the last character that is typed is not read at all. Logging the input value to the console, only yields characters up to the last character.

For instance, when I type the string 'Hello' in the input field, it only logs 'Hell' to the console.

How do I make sure that every character is saved in the enteredFlight variable as soon as it is entered?

CodePudding user response:

You have two ways to do it, the first one is to remove the state value, and update the props with the event directly(looks like you're not using the state for anything):

  const flightInputHandler = (event) => {
    props.flightInput(event.target.value);
  };

In that way you just going to update the props and not handle the state in this component.

If for some reason you need to have the state in this component the easiest way to keep the props up to date with the state is adding an extra useEffect that watches for the state changes like this:

  const [enteredFlight, setEnteredFlight] = useState('');

  React.useEffect(() => {
     props.flightInput(enteredFlight);
  }, [enteredFlight])

  const flightInputHandler = (event) => {
    setEnteredFlight(event.target.value);
  };

CodePudding user response:

State updates are not synchronous in React. You are logging enteredFlight in the handler which will show you the previous value. To properly log enteredFlight, you need to use the useEffect hook with enteredFlight as a dependency.

useEffect(() => {
  console.log(enteredFlight);
}, [enteredFlight]);

useEffect will run every time the state enteredFlight has been modified. Hence, with each keypress you will be able to get your desired result.

  • Related