0

I have an array in my state:

this.state = {
  data: [
    {
      quantity: 0
    }
  ],
  tempQuantity: 0
};

I want to update my data[0].quantity in a TextInput so i use:

onChangeText={tempQuantity =>
  this.setState({
    tempQuantity,
    data: [...this.state.data, { quantity: tempQuantity }]
  })
}

And i have a <Text> to show the result:

<View>
  <Text>{this.state.data[0].quantity}</Text>
</View>

But I get 0 every time!

  1. How can I update each element of each object in an array?

  2. If I use it this way, it will work dynamically? I mean i want to create an object (with all properties of the main object) every time I press a <Button>. [ for example: data[0] with quantity of 10 - data[1] withquantity` of 12 - and ... ]

5
  • You are adding a new object to data on every onChangeText. Commented Aug 9, 2018 at 3:50
  • You are adding a new object to an array if you only have a single object in data array then why not add that as separate property in the state instead of an object inside data array. Commented Aug 9, 2018 at 3:58
  • @Tholle so how can I do this in correct way? Commented Aug 9, 2018 at 4:13
  • @Sandip it's simplified - i have about 15 properties Commented Aug 9, 2018 at 4:13
  • @MohamadKh75 Can you check my answer here stackoverflow.com/a/51758734/1904377. Commented Aug 9, 2018 at 4:15

2 Answers 2

2

To use a single event handler for every element in your array, you could pass in the index as well as the event and update the quantity for the element on that particular index.

Example

class App extends React.Component {
  state = {
    data: [
      {
        quantity: 0
      },
      {
        quantity: 10
      },
      {
        quantity: 100
      }
    ]
  };

  handleChange = (event, index) => {
    const { value } = event.target;

    this.setState(previousState => {
      const data = [...previousState.data];

      data[index] = {...data[index], quantity: value };

      return { data };
    });
  };

  render() {
    return (
      <div>
        {this.state.data.map((element, index) => (
          <div key={index}>
            <input
              type="number"
              value={element.quantity}
              onChange={event => this.handleChange(event, index)}
            />
          </div>
        ))}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

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

Comments

0

You have to modify your data array before setting it to state. You can do it in the following way:

Suppose you have an array with following items:

var data = [
{name: 'a', age: 12},
{name: 'b', age: 15}
]

You need to modify it before setting to state again in the following way:

var newData = data.map((item) => {
return {...item, age: 20}
})

Now your newData will be

var newData = [
{name: 'a', age: 20},
{name: 'b', age: 20}
]

This newData can be assigned to state.

4 Comments

This is an answer for the question 1? So how can I add new object to my array? I want this to be dynamic... (question 2)
I want to edit the age of object[x] not to change all of them to 20!
@MohamadKh75 If you want to update object[x], then you need to update it directly at that index. Like object[x].age = newValue.
@MohamadKh75 for your question So how can I add new object to my array? whatever you are doing was fine for it, it will add new object to existing state array.

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.