Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
Change a JSON value with an MUI Switch component

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
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!