Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update useState into TextInput

I have a simple <TextInput> in React Native and i want to print some text when value change. Its working after second character entered, but not, when user press just one char. I try using functions and even with onChange and take from e.target.value but allways are missing one character at "search" state.

import React, { useState } from 'react';
import { TextInput, View, Text } from 'react-native';

const App = () => {
  const [search, setSearch] = useState('');
  const [searching, setSearching] = useState(false); 
  return(
    <View>
      <TextInput 
        onChangeText={(value) => {
          setSearch(value)
          setSearching(search=='' ? false : true)
        }}
        value = { search }
      />
      {
        searching ?
        (
          <Text>Searching</Text>
        ) : (
          <Text>No searching</Text>
        )
      }
    </View>
  );
} 

export default App

I expect to show "Searching" when TextBox value are not empty.

like image 729
Martin La Regina Avatar asked Oct 16 '25 16:10

Martin La Regina


2 Answers

useState or setState may be asynchronous, so the first time you call setSearch(value), the search state may not be updated yet.

onChangeText={(value) => {
  setSearch(value)
  setSearching(search == '' ? false : true) // "search" is still previous value
}}

Instead, you can directly use value instead for checking.

onChangeText={(value) => {
  setSearch(value)
  setSearching(value == '' ? false : true) // value is latest
}}
like image 114
Ewe Tek Min Avatar answered Oct 19 '25 13:10

Ewe Tek Min


You need to compare the actual value of the TextInput

Using search=='' ? false : true will check the previous state and won't change

onChangeText={(value) => {
  setSearch(value)
  setSearching(search=='' ? false : true)
}}

This will check for the changed value.

onChangeText={(value) => {
  setSearch(value)
  setSearching(value == '' ? false : true) // use value
}}

You need to use value instead of search

Just change this

setSearching(search=='' ? false : true)

to

setSearching(value=='' ? false : true)
like image 42
Vencovsky Avatar answered Oct 19 '25 14:10

Vencovsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!