I am setting the state of an MUI switch based on the response from an API. The Active
field in this API response dictates whether the Switch is checked or unchecked.
The switch is checked if the JSON field is 1
, and un-checked if the field is 0
. When I manually check or un-check the switch, I want to reflect this in JSON by changing the value of Active
to 1
or 0
.
const [checked, setChecked] = useState(true); const [details, setDetails] = useState(""); //This is where my API response is stored function ActivityStatusSwitch() { if (details.Active === 1) { return ( <FormControlLabel control={<Switch checked={checked} onChange={handleSwitchChange} />} label="Active" labelPlacement="start" /> ); } else return ( <FormControlLabel control={<Switch checked={checked} onChange={handleSwitchChange} />} label="Inactive" labelPlacement="start" /> ); } const handleSwitchChange = (e) => { setChecked(e.target.checked); setDetails((prev) => { return { ...prev, Active: e.target.value }; }); };
This is a short example of my JSON:
{ "Active": 1 }
Advertisement
Answer
I’ve always found it easier to use boolean states for situations like this. Since you’re already using 1 & 0, that’s simply true & false.
Therefore, you can do something like this if your Active
field is true/false instead:
const handleSwitchChange = (e) => { setChecked(e.target.checked); setDetails((prev) => { return { ...prev, Active: !prev.Active }; }); };
If you really insist on using 1 & 0, you can still achieve the same thing with a simple conditional.
const handleSwitchChange = (e) => { setChecked(e.target.checked); setDetails((prev) => { return { ...prev, Active: mapActiveValue(prev.Active) }; }); }; const mapActiveValue = (val) => { return val === 0 ? 1 : 0 }