Hellhiem
Hellhiem

Reputation: 123

Push data from multiple inputs to state array

My program generates few inputs and i try to push data to my state's array's

export default class TransmittersTable extends Component {
  constructor() {
    super()
    this.state = {
      axisX: [],
      axisY:[],
      power: [],
    }
  }
  updateAxisX(e) {
    this.setState({
      axisX: this.state.axisX.push(e.target.value)
    })
  }
  updateAxisY(e) {
    this.setState({
      axisY: this.state.axisY.push(e.target.value)
    })
  }
  updateAxisPower(e) {
    this.setState({
      power: this.state.power.push(e.target.value)
    })
  }
  generateTransmittersItems(){
    let transmitters = [];
    for(let i = 0; i < this.props.numberOfTransmitters; i++) {
      transmitters.push(
        <tr>
          <td><input id={i} ref="axisX" type="text" onChange={this.updateAxisX.bind(this)}/></td>
          <td><input id={i} ref="axisY" type="text" onChange={this.updateAxisY.bind(this)}/></td>
          <td><input id={i} ref="power" type="text" onChange={this.updateAxisPower.bind(this)}/></td>
        </tr>
      );
    }
    return transmitters
  }
  componentWillMound(){}
  render() {
    return (
      <table>
        <thead>
          <tr>
            <th>Axis X</th>
            <th>Axis Y</th>
            <th>Power</th>
          </tr>
        </thead>
        <tbody>
          {this.generateTransmittersItems()}
        </tbody>
      </table>
    )
  }
}

In first row of inputs evrything is okay but if i try to push another value form another row of input's to the same state array (ex. axisX) my console send me this error "this.state.axisX.push is not a function". What i did wrong and what i have to do to push more values to the same array from input using the same function?

Upvotes: 1

Views: 2145

Answers (1)

Wei
Wei

Reputation: 372

I think the problem isn't related to the react state issue. When you used the "push" methods, it won't return an array but return the length of the array, and that is the reason why when you use "push" method in second time will get the error "this.state.axisX.push is not a function".

So, if you need to change your state, you can just use "concat" method like this to get a new array as return:

this.setState({
  axisX: this.state.axisX.concat([e.target.value])
})

var a = ["Hi", "There"];
var b = a.push("Oh");

console.log(b); // get 3, not an array
console.log(a); // ["Hi", "There", "Oh"]

Upvotes: 1

Related Questions