I have declared an array of objects in the state that represent TextInput fields. Now I want to add value onChangeText of my inputs but as soon as I try to write something on the input I get the error: 'this.state.sede_array is not a function'. I did console.log of the array and I see that only the first letter of my input is added to the value property and then the error fires up. Please help to figure out what is happening.

export default class Form extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sede_array:[
        {id:1, value:null},
        {id:2, value:null},
        {id:3, value:null},
      ]

    };
  }

  render() {
    console.log(this.state.sede_array)
    let sede_list= this.state.sede_array.map((val, key) => {
      return(
      <View key={key}>
        <Text style={styles.titolo}>Indirizzo Sede 
        {this.state.sede_array[key].id}</Text>

      <TextInput style={styles.input}
        onChangeText={value => {
          sede_array[key].value = value;
          this.setState({sede_array})
        }}
      />
      </View>
    )});

1 Answers

0
Rob Brander On

I have a feeling you are clobbering your array. Inside the onChangeText event handler, you are setting state; but do you know what the value is? You use sede_array without (this.state) as a prefix. I'm assuming sede_array variable doesn't exist globally, thus it would assign 'undefined' to this.state.sede_array when you call setState(). Since setState will trigger another render, on that render cycle it would crash because this.state.sede_array would be undefined. You can fix this by adding this.state. infront of sede_array inside onChangeText.