Reputation: 2702
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!
How can I update each element of each object in an array?
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] with
quantity` of 12 - and ... ]
Upvotes: 0
Views: 4774
Reputation: 112777
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>
Upvotes: 2
Reputation: 2459
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
.
Upvotes: 0