Reputation: 33
I have a problem when trying to get values from object and pass it to child. This is my code :
let listDomestic = this.state.domesticArray.map((item) =>
<DomesticItem
key={item.id}
index={item.index}
deleteMethod={() => this.deleteDomesticElement(key)}
/>
);
the problem is on key={item.id}
and index={item.index}
, so key
and index
are undefined, I see this by printing them in child
My function to add objects in domesticArray
is like so:
addDomesticItem() {
let id = Date.now();
let index = this.state.domesticArray.length;
let newItem = {
id: id,
index: index,
quantity: 0,
watt: 0,
duration: 0,
whDay: 0,
}
let newDomesticArray = [...this.state.domesticArray];
newDomesticArray.push({
newItem
});
this.setState({
domesticArray: newDomesticArray
});
}
Upvotes: 1
Views: 446
Reputation: 1074208
Your code is creating a new object and setting newItem
as a property on it (the property's name is newItem
, you're using shorthand property notation unintentionally), then pushing that new item into the array.
The minimal change is to change this:
newDomesticArray.push({
newItem
});
to this:
newDomesticArray.push(newItem);
But:
You need to use the callback version of setState
, not the version you pass an object to. That's because you're setting new state based on existing state, and [state updates are asynchronous and may be combined][1].
We can make that more concise. :-)
So just addressing those two things, and using parameter destructuring:
addDomesticItem() {
this.setState(({domesticArray}) => {
const newItem = {
id: Date.now(),
index: domesticArray.length,
quantity: 0,
watt: 0,
duration: 0,
whDay: 0,
};
return {domesticArray: [...domesticArray, newItem]};
});
}
But (part 2):
I recommend that you don't rely on Date.now
for id
. If you ever end up adding two items within the same millisecond (remember, computers are fast), they won't have unique IDs.
I recommend that you don't include the index of the item in the array in the item itself, since it makes maintaining the entries in the array difficult.
Instead, I'd have an ever-increasing counter in your component that you use for id
values. In your constructor:
this.idAllocator = 0;
and then:
addDomesticItem() {
this.setState(({domesticArray}) => {
const newItem = {
id: ++this.idAllocator,
quantity: 0,
watt: 0,
duration: 0,
whDay: 0,
};
return {domesticArray: [...domesticArray, newItem]};
});
}
and then:
let listDomestic = this.state.domesticArray.map((item, index) =>
<DomesticItem
key={item.id}
deleteMethod={() => this.deleteDomesticElement(key)}
/>
);
and then when you need to find the item in this.state.domesticArray
, you use find
:
const item = this.state.domesticArray.find(item => item.id === id);
or findIndex
to find its index:
const index = this.state.domesticArray.findIndex(item => item.id === id);
and remember that if you're going to use that index
to modify domesticArray
, you need to do that in a setState
callback.
Upvotes: 2