typescriptreact-nativereact-hookstextinputreact-native-textinput

React Native - useState - Text Input field is not clearing the first character from state after I delete all text from input


My problem is that when I enter on the airline textInput for example "TEST" and when I enter the delete keyboard button, the last character stays in the state ex: "T", but in view it shows like its fully deleted. With console.log(routes) I can see that the last character T is still in the object. Below is my code


Solution

  • You are setting the airline state via the function setAirline in the onChangeText callback function in the Airline component, but you are using the internal state called state of this component which you are setting after you are setting the airline equal to state.

    This lines of code should be the problem.

    onChangeText={el => {
      setAirline(state);
      setState(el);
    }}
    

    airline is never equal to el. Suppose the state is equal to TEST. We delete one character. T is removed and the onChangeText callback function is called and el is equal to TES, but you are calling setAirline(state) before setState(el), hence in that very moment state is still equal to TEST. The airline will not be updated correctly.

    If you delete everything, then the last character will never be removed from the airline state.

    One possible solution is to just use the callback value of the function for the airline as well.

    onChangeText={el => {
      setAirline(el);
      setState(el);
    }}
    

    But in this case we might ask: why are we creating a new state anyway? Instead, pass the airline state along with its setter function to the component and use it as usual.

    <Airline airline={airline} setAirline={setAirline} emptyField={emptyAirline} />
    
    xport const Airline = ({ setAirline, airline }: AirlineProps): JSX.Element => {
      return (
        <TextInput
          title={getAirline + ' (optional)'}
          value={airline}
          onChangeText={el => {
            setAirline(el);
          }}
        />
      );
    };