react js : input toggle swich not toggling on onChnage

Viewed 22

i have a toggle swicth

 <label class="switch">
        <input
          type="checkbox"
          id="checked"
          checked={domestic_voilence}
          onChange={handleChangeTogle}
        />

        <span class="slider"></span>
      </label>

from api i am getting value wether my toggle swich is true or false

 useEffect(() => {
  axios
      .get(
        `analytics/get-personal-details/?customer=` +
          22,
        {
          headers: {
            "Content-Type": "application/json",
            Accept: "application/json",
            Authorization: `token  6fa443340e173e8013ee91ccdd518d3dc9113046`
          }
        }
      )
      .then((res) => {
        console.log(res.data);

        setdomestic(res.data[0].domestic);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

using on change i am trying to change the value of toggle swich

 const handleChangeTogle = (e) => {
  
    setdomestic(!domestic);
   
  };

when submit button is clicked i want to submit data to api


const SubmitData = () => {
    console.log(domestic);
  };

working code i have made codesandbox

2 Answers

You are passing the wrong value, it should be

          <input
            type="checkbox"
            id="checked"
            checked={domestic}
            onChange={handleChangeTogle}
          />

instead of the original

          <input
            type="checkbox"
            id="checked"
            checked={domestic_voilence}
            onChange={handleChangeTogle}
          />

Also when on component mount, set your checkbox value from the result

setdomestic(res.data[0].domestic_voilence);

Edit strange-edison-onopz9

Related