I have data in parent's component state like this:
data=[
{key:0,name="abc",value="123"},
{key:1,name="def",value="456"},
{key:2,name="ghi",value="789"}
]
In my react component I am calling child components as list in the return part of the parent component as shown below.
class MyApp extends React.Component{
constructor(props) {
super(props);
this.state = {
record={
name="",
timestamp="",
data =[
{key:0,name="abc",value="123"},
{key:1,name="def",value="456"},
{key:2,name="ghi",value="789"}
]
}
this.deleteFromStateArray=this.deleteFromStateArray.bind(this);
}
deleteFromStateArray(key){
let oldData = [...this.state.record.data];
let newData= [];
oldData.map(function (record, i) {
if (record.key != key) {
newData.push(record);
}
})
newData.map(function (record, i) {
newData[i].key = i + 1
})
this.setState({ record: Object.assign({}, this.state.record, { data: newData }), });
}
render() {
return(
{
this.state.data.map((record,index) =>
<Child key={record.key}
id={record.key}
name={record.name}
value={record.value}
onDelete={this.deleteFromStateArray} />
}
)
}
I am calling onDelete() in the child component like this
<button onClick={this.props.onDelete(this.state.id)} />
\\ I am initializing id as key in state inside constructor in child
My problem is when I am calling onDelete in the child class I am able to remove the obj with key=1 properly in the function but rerendering is not happening properly.
What I mean is state is getting set properly with only 2 items in data 1 with key=0 and other with key=2. But what i see in GUI is 2 child components 1 with key 0 and second one with key=1 which is cxurrently not present in the state data.
Can anybody help me with re-rendering the data properly?
I also want to change the key ordering after deleting from array in setState