Mohamed Ahmed
Mohamed Ahmed

Reputation: 223

How to set an array of multiple data as a state

So basically I want to be able to collect all the values from multiple inputs and set that array as a state. Here is what I am currently working with:

this.state.basket.map(b => {
  return (
    <View>
      <InputSpinner
        style={styles.spinnerQty}
        max={50}
        min={1}
        step={1}
        rounded={false}
        showBorder
        colorMax={"#2a292d"}
        colorMin={"#2a292d"}
        value={b.qty}
        onChange={num => {
          this.setState({ popUpQty: num });
        }}
      />

      <View style={styles.hrLine}></View>
    </View>
  );
});

So I am iterating my basket and setting a spinner with a value from axios output. So there are now multiple InputSpinner with multiple values. My question is, how can I collect all the values of the onChange, and push it to an array which will eventually become a state. Something like QuantityState: [] would be the values of all the InputSpinner. Hope that made sense. Any help is appreciated. Thanks!

PS. InputSpinner is an npm package from here.

Upvotes: 0

Views: 158

Answers (1)

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

Through this code you can dynamically add/update onChange number on it's particular array instance. num key will be added when a particular onChange trigger so at the end you will get its values which placed on it's index and if key not found that means onChange never triggered for that index

state = {
        spinnerData : {},
        basket: []
    }



    this.state.basket.map((b, index) => {
      return (
        <View>
          <InputSpinner
            style={styles.spinnerQty}
            max={50}
            min={1}
            step={1}
            rounded={false}
            showBorder
            colorMax={"#2a292d"}
            colorMin={"#2a292d"}
            value={b.qty}
            onChange={num => {
              const newbasket = [...this.state.basket];
              newbasket[index]["num"] = num;
              this.setState({ basket:newbasket });
            }}
          />

          <View style={styles.hrLine}></View>
        </View>
      );
    });

Upvotes: 2

Related Questions