When "Reset" is clicked, I want to make the page the first appearance. When I click "Reset" first, it resets to the first appearance. However, when I change the obj1 state again and click "Reset", it won't be back. Instead, the obj1 is referenced.
My question is,
- What's wrong with the "handleReset" function? Why can't it be updated by obj2?
- Instead of using window.location.reload(), how can I make the page the first state that nothing hasn't changed? I was thinking of keeping obj1 in variable somewhere and when handleReset is called, it could feed the obj1 state. But I'm not sure how to realize that..
- I'm using React Developer Tools but Uncaught Error happens. What's causing it?
*First appearance that obj1.id and obj1.num are displayed. enter image description here
*When I change the obj1 state again and click "Reset", it won't be back. Instead, the obj1 is referenced. enter image description here
*Uncaught Error: Cannot add node "1" because a node with that id is already in the Store. enter image description here
App class(Parent)
class App extends Component {
state = {
obj1: [
{ id: 1, num: 0 },
{ id: 2, num: 1 },
{ id: 3, num: 2 },
],
obj2: [
{ id: 1, num: 0 },
{ id: 2, num: 1 },
{ id: 3, num: 2 },
],
};
handleReset = () => {
const obj2 = [...this.state.obj2];
this.setState({ obj1: obj2 });
};
handleDelete = (id) => {
console.log("id", id);
const obj1 = this.state.obj1.filter((obj) => obj.id !== id);
this.setState({ obj1 });
};
handleIncrement = (counter) => {
const temState = [...this.state.obj1];
temState[counter - 1].num++;
this.setState({ obj1: [...temState] });
};
render() {
return (
<div>
<Counters
obj1={this.state.obj1}
onReset={this.handleReset}
onHandleDelete={this.handleDelete}
onHandleIncrement={this.handleIncrement}
/>
</div>
);
}
}
Counters class(child of App class)
class Counters extends Component {
render() {
return (
<div>
<span onClick={this.props.onReset} className="badge bg-primary m-2">
Reset
</span>
{this.props.obj1.map((obj) => (
<Counter
key={obj.id}
//props
handleIncrement={this.props.onHandleIncrement}
handleDelete={this.props.onHandleDelete}
counter={obj}
/>
))}
</div>
);
}
}
Counter class (controlled by Counters class)
class Counter extends Component {
render() {
return (
<div>
<span className="badge bg-primary">{this.props.counter.num}</span>
<button
onClick={() => this.props.handleIncrement(this.props.counter.id)}
className="badge bg-secondary m-2 "
>
BUTTON
</button>
<span
onClick={() => this.props.handleDelete(this.props.counter.id)}
className="badge bg-danger m-2"
>
DELETE
</span>
</div>
);
}
}