React Rendering Deleted Array Element After Setstate()
I'm having an issue where React seems to be rendering a deleted array element after I've removed it from an array in the components state. After setState(), rendering is triggered,
Solution 1:
Few things.
When you want to set the state, based on the prev state, use the setState
with a callback, which takes as argument the prevState. So the next code:
handleValueChange = event => {
const { name, value } = event.target;
const { id, notes } = this.state;
let newState = {
id: id,
notes: value
};
this.setState(newState);
};
Will be something like:
handleValueChange = event => {
const { name, value } = event.target;
const { id, notes } = this.state;
this.setState(prevState => ({ id: prevState.id, notes: value}));
};
Same in the below component:
handleDelete = id => {
const newNotes = ;
this.setState(prevState => ({ notes: R.filter(note => note.id !== id, prevState.notes) }));
};
And so on for all the times that you update the state based on previous state value.
Then when you do create a list of elements in react, use key
property:
<SessionNoteGroupkey={id}id={id}notes={notes}onDelete={this.handleDelete}index={i + 1}
/>
That's used by react for managing the render of list of items
Solution 2:
Try adding a key to the container div of your render
return (
<divkey = {this.props.id}><Gridcontainer><Griditemxs={12}><TextFieldmultilinefullWidthid="notes"name="notes"label="Notes"rows="2"value={notes}onChange={this.handleValueChange}
/></Grid></Grid><Buttonvariant="outlined"color="primary"onClick={this.handleDelete}>
Delete
</Button></div>
);
Post a Comment for "React Rendering Deleted Array Element After Setstate()"