Search code examples
react-nativestatetextinput

Save value of textInputs on call function React-Native


I am fetching some TextInputs from an API and pushing them to an Array. Then I am saving the input text from user and all keys and values that a textinput object has. However, when I save, it saves every time I make a change on the text. I want to save and push everything to the array when I call a function further down in View. Basically, I want the state to be pushed to array only once I call a function, not every time I change text.

I appreciate any suggestion! Please let me know if the question is not clear enough.

myInputFields = {
   myTextFields: [],
};

textfieldsObject = () => {
const obje = this.props.navigation.state.params.item;
var keyvalue_to_json = JSON.parse(obje.keyValues);
var foundTextFields = [];

for (let i = 0; i < keyvalue_to_json.inputFields.length; i++) {
  if (keyvalue_to_json.inputFields[i].type === 'textfield') {
    foundTextFields.push(<TextInput style={{ borderWidth: 1 }}

      onChangeText={(text) => {
        keyvalue_to_json.inputFields[i].inputValues = text;
        this.myInputFields.myTextFields.push(keyvalue_to_json.inputFields[i])
      }}
    >{keyvalue_to_json.inputFields[i].placeholderText}</TextInput>)</Text>)
  }
}

}


Solution

  • onChangeText event will be invoked every time when you type or change text. You need to use onEndEditing event which is triggered only when the text input ends. So your TextInput code will be:

    <TextInput style={{ borderWidth: 1 }}
      onEndEditing={(e) => {
        keyvalue_to_json.inputFields[i].inputValues = e.nativeEvent.text;
        this.myInputFields.myTextFields.push(keyvalue_to_json.inputFields[i])
      }}
    >{keyvalue_to_json.inputFields[i].placeholderText}
    </TextInput>