i have a little try which i also leave the CodeSandbox link below. I have 3 checkboxes. I update the count
value according to the checked status of the checkboxes. 2 of the checkboxes are selected by default. I have a dummyArray and I am sending the name
, value
, isPreselected
values to the checkboxes as props by returning them with map. So when the page loads, my count
value should be 10, but it is 5. I tried increasing the count
value with useEffect
if the checkbox was selected when it was loaded for the first time, but I guess it only adds the value for the first checkbox, not the second one. I also tried to foreach
the whole array on page load and update the count
value if the isPreselected
value is true
, but still the same result. How can I fix this?
CodeSandbox Link: https://codesandbox.io/s/silly-liskov-egpq2s
CodePudding user response:
Inside the useEffect callback, you can iterate over the dummyArray and add the value of each checkbox that is preselected to the count.
import Checkbox from "./Checkbox";
const dummyArray = [
{ name: "checkbox 1", value: 5, isPreselected: true },
{ name: "checkbox 2", value: 5, isPreselected: true },
{ name: "checkbox 3", value: 5, isPreselected: false }
];
export default function App() {
const [count, setCount] = useState(0);
useEffect(() => {
const initialValue = 0;
const preselectedValues = dummyArray
.filter((item) => item.isPreselected)
.map((item) => item.value);
const total = preselectedValues.reduce(
(accumulator, currentValue) => accumulator currentValue,
initialValue
);
setCount(total);
}, []);
return (
<div>
{dummyArray.map((item, index) => (
<Checkbox
key={index}
name={item.name}
value={item.value}
isPreselected={item.isPreselected}
count={count}
setCount={setCount}
/>
))}
<p>{count}</p>
</div>
);
}
CodePudding user response:
The problem is your initial value at setState. Should be 10 but you set to 0 in this case. To count five for each selected box you can do this:
const [count, setCount] = useState(dummyArray.filter(item=>item.isPreselected).length * 5);
It will count the boxes checked and multiply by 5.