I am trying to re-render the checked state of below component, even though the isChecked state comes as false, the useState is not updating to the set prop value, instead it maintains the old state.
const CheckListItem = ({ label, onChangeEventHandler, isChecked, index }) => {
const [checked, setChaecked] = useState(isChecked || false);
console.log(`${label} checked => `, isChecked); \\ false
console.log(`${label} checked => `, checked); \\ true || maintaining the old state.
const localOnChangeHandler = (ev) => {
if (typeof onChangeEventHandler === "function") {
setChaecked(ev.target.checked);
onChangeEventHandler(index, ev.target.checked);
}
};
useEffect(() => {
console.log(`in useEffect ${label} checked => `, isChecked);
setChaecked(isChecked);
}, [isChecked, label]);
return (
<li key={index}>
<label>
<input
type="checkbox"
checked={checked}
onChange={localOnChangeHandler}
/>
{label}
</label>
</li>
);
};
checked should have the correct value which is set in the isChecked prop
useState is working as intended, the value passed to it is only its initialState and if even if that value changes it will not update the stored value.
See React's docs about Resetting all state when a prop changes - rather than complicate your code you can pass a key from the parent to create a new component instance and thereby pass a new initialState:
<CheckListItem
initialIsChecked={initialIsChecked}
{/* When `initialIsChecked` changes, a new
* `CheckListItem` instance will be created` */}
key={initialIsChecked}
/>
There's a typo in setChaecked(ev.target.checked); change it to setChecked(ev.target.checked);
And also try this code
const CheckListItem = ({ label, onChangeEventHandler, isChecked, index }) => {
const localOnChangeHandler = (ev) => {
if (typeof onChangeEventHandler === "function") {
onChangeEventHandler(index, ev.target.checked);
}
};
return (
<li key={index}>
<label>
<input
type="checkbox"
checked={isChecked}
onChange={localOnChangeHandler}
/>
{label}
</label>
</li>
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With