I want to have a checkbox with a defaultChecked value matching the value in my database. My current issue is that defaultChecked is always false, even when the database value is true.
Here is my current thinking + code:
I store the defaultChecked as a state:
const [defaultEnabled, setDefaultEnabled] = useState(false);
I then use a useEffect hook to read from the database once at the start of the page loading.
useEffect(() => {
const fetchEnabled = async () => {
const reference = ref(db, 'Permissions/');
onValue(reference, (snapshot) => {
setDefaultEnabled(snapshot.val());
// This read to the database works - that is, snapshot.val() does indeed return the correct boolean value
});
};
fetchEnabled();
}, []);
And lastly I have the checkbox itself [the handleChecked function works and does not effect the state].
<input type='checkbox' onChange={handleChecked} defaultChecked={defaultEnabled}/>
I suspect the issue comes from the useState(false) at the start, but my understanding was that when the useEffect is ran, it would update the state, and this would cause the checkbox to re-render with the correct value.
Any help would be much appreciated!
2
Answers
The issue is that
defaultChecked
needs a value at the first moment it's rendered, and so it uses the initialuseState
value of false instead of waiting for the useEffect.This can be solved by doing
checked={defaultEnabled}
, since the state will update this non-default checked attribute.you can install yn library and set state as like as below.