1

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?

2
  • id should be unique isn't it? Commented Apr 16, 2017 at 12:14
  • also imo you should use this:facebook.github.io/react/docs/… Commented Apr 16, 2017 at 12:17

1 Answer 1

1

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"]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.