CoderLBY
CoderLBY

Reputation: 89

react APP input box always shows one char less, why?

I have a question, in my react App, I should check if the input value already exists, if yes, then gives an alert. The question is my input box always displays one char less than the whole word("li" in the box, "liu" in alert), why is this the case ? Please see picture for better understanding.

here is some code:

const handleNameChange = (event) => {
    const{value} = event.target
    //console.log('vaue', value)
    if (persons.find(({name})=> name === value)) {
      return window.alert(`${value} is already added to phonebook`)
    }
    return setNewName(value)
  }

  return (
    
    <div>
      
      <h2>Phonebook</h2>
      <form onSubmit={addName}>
        <div>
          name: <input value={newName} onChange={handleNameChange}/>
        </div>
        <div>
          <button type="submit">add</button>
        </div>
      </form>

enter image description here

Upvotes: 0

Views: 302

Answers (1)

Honghai Mei
Honghai Mei

Reputation: 81

The input is binding with the state newName, but in your handleNameChange function, it would skip the setNewName if that value is in the persons. Therefore, what you can do is:

if (persons.find(({name})=> name === value)) {
    setNewName(value)
    window.alert(`${value} is already added to phonebook`)
    return;
}
    setNewName(value);

That would fix the issue

Upvotes: 1

Related Questions