Hi. I’m new to this forum. I need help and get anyone’s idea if my code in the handleIncrement() is a valid way to update the state. I’m taking Mosh’s React course and I am following his coding. I just want to get some confirmation if the following code is a valid way to update the state of a component:
//parent component
class Counters extends Component {
state = {
counters: [
{ id: 1, value: 4 },
{ id: 2, value: 3 },
{ id: 3, value: 2 },
{ id: 4, value: 0 },
],
};
handleDelete = (counterId) => {
//console.log(“Delete event called”);
const counters = this.state.counters.filter(© => c.id !== counterId);
this.setState({ counters });
};
handleReset = () => {
const counters = this.state.counters.map(© => {
c.value = 0;
return c;
});
this.setState({ counters });
};
//this handleIncrement function is called inside the onClick method of a controlled component //called see below code
handleIncrement = (counter) => {
console.log(counter);
const value = counter.value++;
this.setState({ value });
};
render() {
return (
Reset
{this.state.counters.map((counter) => (
))}
);
}
}
export default Counters
//Controlled Component which utilizes the handleIncrement()
class Counter extends Component {
render() {
return (
{this.formatCount()}
<button
onClick={() => this.props.onIncrement(this.props.counter)}
className="btn btn-secondary btn-sm "
>
Increment
<button
onClick={() => {
this.props.onDelete(this.props.counter.id);
}}
className=“btn btn-danger btn-sm m-2”
>
Delete
);
}
getBadgeClasses() {
let classes = “badge m-2 badge-”;
classes += this.props.counter.value === 0 ? “warning” : “primary”;
return classes;
}
formatCount() {
const { value } = this.props.counter;
return value === 0 ? “Zero” : value;
}
}
export default Counter;