Started today learning react and i ran into an issue that might be more JS related than actually react.
import React, { useState } from "react";
import Counter from "./counter";
function Counters() {
const [counters, setCounters] = useState([
{ id: 1, value: 4 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
]);
const handleDelete = (counterID) => {
setCounters(counters.filter((counter) => counter.id !== counterID));
};
const handleIncrement = (counterToBeUpdated) => {
console.log(counters);
const counters = [...counters];
const index = counters.indexOf(counterToBeUpdated);
counters[index] = { ...counterToBeUpdated };
counters[index].value++;
setCounters({ counters });
};
return (
<div>
{counters.map((counter) => (
<Counter
key={counter.id}
counter={counter}
onDelete={handleDelete}
onIncrement={handleIncrement}
/>
))}
</div>
);
}
export default Counters;
When child component calls handleIncrement i get the Reference error of trying to access counters before it was initialized.