0

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

coder03
  • 61
  • 8

1 Answers1

1

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);
      }}
    />
  );
};
David Scholz
  • 8,421
  • 12
  • 19
  • 34
  • 1
    Your solution works perfect, but the only problem I have is that when I switch the dropdown value and I comeback to the Route Fields screen, the state of airline doesn't get reset to the initial value. I have tried to do it with the solution below, but it doesn't work. `navigation.addListener(ON_SCREEN_FOCUS, () => { setAirline(''); }); navigation.addListener(ON_SCREEN_BLUR, () => { setAirline(''); });` Anyway your solution fixes my first problem so thank you very much :) – coder03 Aug 21 '22 at 17:42
  • What you are trying to achieve is very well explained [here in the official documentation](https://reactnavigation.org/docs/function-after-focusing-screen/). – David Scholz Aug 21 '22 at 21:10