skip to Main Content

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


  1. Chosen as BEST ANSWER

    The issue is that defaultChecked needs a value at the first moment it's rendered, and so it uses the initial useState 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.


  2. you can install yn library and set state as like as below.

    1. npm install yn
    2. setDefaultEnabled(yn(snapshot.val()));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search