Search code examples
react-nativesavestaterendertextinput

Save state of TextInput array - React Native


I am fetching from API multiple TextInputs and displaying them on my screen. So, how can I save the state of user inputs to a global object. Something like this:

    state = {
    foundtextfields: []
   }

Here I am pushing those fetched TextInputs to foundTextFields[] array:

var foundTextFields = [];

    foundTextFields.push(<TextInput>{keyvalue_to_json.inputFields[i].placeholderText}</TextInput>)

And I am displaying text inputs in this list:

return (
    <View>
      {foundtextfields}
    </View>
)

EDIT: I want to loop through the state of the array, and extract the key from that ex. “key” (signedbyFullName) and match if that is the same with the json body property "signedbyFullName" like below.

  postToBmp = (obje) => {
var userArray = [];
for (i = 0; i < this.myInputFields.myTextFields.length; i++) {
       userArray.push(this.myInputFields.myTextFields[i])
       console.log("this is the title of al inputFields:",   this.myInputFields.myTextFields[i].key)
}

fetch('URL', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    'Connection': 'Keep-Alive',
  },
  credentials: 'include',

  body: JSON.stringify({

    from: '[email protected]',

    to: ['<[email protected]>'],

    signedByFullName: '',

    signedByCPRNumber: '',

    otherCompanyName: '',

    otherCompanyCVRNumber: ''
  })
})

}


Solution

  • To store the values you can create an array along side foundtextfields with the values, and every time you change a text you set it to the index of the other array
    Like so:

        foundTextFields.push(
          <TextInput 
             onChangeText={(text) =>{
                let inputValues=this.state.inputValues;
                inputValues[i]=text;
                this.setState({inputValues})
             }}>
            {keyvalue_to_json.inputFields[i].placeholderText}
          </TextInput>)
    

    OR

    foundTextFields.push(
          <TextInput 
             onChangeText={(text) =>{
                keyvalue_to_json=this.state.keyvalue_to_json
                keyvalue_to_json.inputFields[i].inputValues=text;
                this.setState({keyvalue_to_json})
             }}>
            {keyvalue_to_json.inputFields[i].placeholderText}
          </TextInput>)