Parth
Parth

Reputation: 87

onClick event not working on first click in react

In here when i press the search button the first time the 'username' state doesn't recieve any data. The 'username' state is empty and the API request in the App.js fails. The second time i click the same button everything works as expected. How do i make it work on the first click ? What's wrong here?

const Search = ({setInputText, setUsername, inputText, username}) => {

    const inputHandler = (e)=> {
        setInputText(e.target.value)
    }

    const searchHandler = (e)=> {
        e.preventDefault()
        setUsername(inputText)
    }

    return (
        <div>
            <form>
                <input value={inputText} onChange={inputHandler} type="text"/>
                <button onClick={searchHandler}>Search</button>
            </form>
        </div>
    )
}

EDIT : ADDING App.js here

function App() {

  //States
  const [inputText, setInputText] = useState("")
  const [username, setUsername] = useState("")
  const [stats, setStats] = useState([])

  return (
    <div className="App">
        <h1>Game Stats</h1>
        <Search setInputText={setInputText} setUsername={setUsername} inputText={inputText} username={username} setStats={setStats}/>
        <Stats stats={stats}/>
    </div>
  );
}

Upvotes: 6

Views: 12470

Answers (4)

Nicholas Mberev
Nicholas Mberev

Reputation: 1841

If your component is inside ScrollView component, and you come across this behavior, add this keyboardShouldPersistTaps={true} to the ScrollView.

Upvotes: -1

briancoder
briancoder

Reputation: 159

So first you should use a callback like so :

onClick={(e)=>searchHandler(e)}

If you have handleBlur in your input element please remove because these states usually interfere so the button wont update on first click but on second. Had the same problem myself and this resolved it.

Upvotes: 3

Mrmld Sky
Mrmld Sky

Reputation: 149

For me helped something like <button onClick={(e) => searchHandler(e)}>Search</button> after I read there

seems that the events where overlaping

Upvotes: 1

Lorenzo
Lorenzo

Reputation: 112

You may want to try the following and move searchHandler as the value of onSubmit in the <form> tag

<form onSubmit={(e) => searchHandler(e)}>
  <input value={inputText} onChange={inputHandler} type="text"/>
  <button type="submit"> Search </button>
</form>

More on https://reactjs.org/docs/forms.html

Upvotes: 0

Related Questions