Home > other >  How to reflect the backend state (true, false) to toggle in React.js?
How to reflect the backend state (true, false) to toggle in React.js?

Time:01-04

I am using React.js to create the front-end side of a web application that can control home appliances.

What I want to achieve is I want the toggle to reflect the state of the backend.

The device (sensor) has a field called armed. I want the toggle to be ON when it is true and OFF when it is false but I don't have an idea... Not reflected now as you can see photo. . .

enter image description here

Json

{
    "attributes": {
        "sensor": [
            {
                "object_id": "0x0082_38",
                "armed": true,
            },
        ],
    }
}

ToggleSwitchButton.js

import React from 'react'
import styled from 'styled-components'

const StyledToggleSwitchButton = styled.div`
    & input {
        display: none;
        &:checked   label {
            background-color: #7CFC00;
            &::before {
                left: 2em;
            }
        }
    }

    & label {
        background-color: #062863;
        border-radius: 2em;
        border: 2px solid var(--text-color);
        display: flex;
        align-items: center;
        justify-content: space-around;
        height: 2em;
        position: relative;
        transition: .5s;
        width: 3.75em;

        &::before {
            background: #fff;
            border-radius: 100%;
            content: '';
            display: inline-block;
            height: 1.5em;
            position: absolute;
            left: 0.25em;
            transition: .5s ease-out;
            width: 1.5em;
            z-index: 2;
        }
    }

    @media(max-width:751px){
        & input {
            display: none;
            &:checked   label {
                background-color: #7CFC00;
                &::before {
                    left: 1em;
                }
            }
        }
    
        & label {
            background-color: #062863;
            border-radius: 1em;
            border: 1px solid var(--text-color);
            display: flex;
            align-items: center;
            justify-content: space-around;
            height: 1em;
            position: relative;
            transition: .5s;
            width: 1.75em;
    
            &::before {
                background: #fff;
                border-radius: 100%;
                content: '';
                display: inline-block;
                height: 1em;
                position: absolute;
                left: 0.2em;
                transition: .5s ease-out;
                width: 1em;
                z-index: 2;
            }
        }

    }
    
    
    @media(max-width:282px){
        @media(max-width:751px){
            & input {
                display: none;
                &:checked   label {
                    background-color: #7CFC00;
                    &::before {
                        left: 1em;
                    }
                }
            }
        
            & label {
                background-color: #062863;
                border-radius: 1em;
                border: 1px solid var(--text-color);
                display: flex;
                align-items: center;
                justify-content: space-around;
                height: 1em;
                position: relative;
                transition: .5s;
                width: 1.75em;
        
                &::before {
                    background: #fff;
                    border-radius: 100%;
                    content: '';
                    display: inline-block;
                    height: 1em;
                    position: absolute;
                    left: 0.2em;
                    transition: .5s ease-out;
                    width: 1em;
                    z-index: 2;
                }
            }
    
    }
    
`

const ToggleSwitchButton = ({ className, handleChange }) => (
    <StyledToggleSwitchButton className={className}>
        <input id="btn-mode" type="checkbox" onChange={handleChange} />
        <label htmlFor="btn-mode">
    </label>
  </StyledToggleSwitchButton>
)

export default ToggleSwitchButton;

SensorDetail.js

import ToggleSwitchButton from '../../ToggleSwitchButton'

const SensorDetail = (props) => {

    const { object_id } = useParams();
    
    const [sensor, setSensor] = useState([]);
    
    const [isToggle, setIsToggle] = useState();
    const [toggle_status, setToggleStatus] = useState();
  
    const handleChange = useCallback(() => {
      // Executed when the toggle switch is turned on or off
        if(isToggle) {
          setIsToggle(false);
          alert('switch off!');
          setDisarm();
        }
        else{
          setIsToggle(true);
          alert('switch on!');
          setArm();
        }
    }, [isToggle]);


    const getDevices = async(data) => {
      await axios.get('xxx.com',
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${cookies.get('accesstoken')}`
          },
        })
        .then(result => {
          setSensor(result.data.attributes.sensor);  
          // get the arm status
          setToggleStatus(result.data.attributes.sensor.filter(c => c.object_id === object_id).map((item,i) =>  item.armed)[0]);  
           // toggle_status contains the backend toggle status (armed is true, disarmed is false).
           // If toggle status is true here, setIsToggle(true) to true isToggle,
           // If the toggle status is false here, setIsToggle(false) sets isToggle to false.
           // (setIsToggle(true) toggles ON, setIsToggle(false) toggles OFF)
          if (result.data.attributes.sensor.filter(c => c.object_id === object_id).map((item,i) =>  item.armed)[0] == true) {
            setIsToggle(true);
          }
          else {
            setIsToggle(false);
          };
    
        })
        .catch(err => {
          console.log(err);
        });
    }
    
    useEffect(() => {
      getDevices();
    },[]);

    return (
        <div>
            <p>Device Status</p>
            <div>
            {item.armed == true ?
              <p>Armed</p>
            :
              <p>Disarmed</p>
            }
            <ToggleSwitchButton handleChange={handleChange} />
    
        </div>
    );
}
export default SensorDetail;

CodePudding user response:

Pass a boolean prop to the ToggleSwitchButton component representing isToggle:

const ToggleSwitchButton = ({ className, checked, handleChange }) => (
    <StyledToggleSwitchButton className={className}>
        <input id="btn-mode" type="checkbox" onChange={handleChange} checked={checked}/>
        <label htmlFor="btn-mode">
    </label>
  </StyledToggleSwitchButton>
)

Also, set isToggle value to a default and pass it to the component:

const [isToggle, setIsToggle] = useState(false);

...

return (
    <div>
        <p>Device Status</p>
        <div>
        {item.armed == true ?
          <p>Armed</p>
        :
          <p>Disarmed</p>
        }
        <ToggleSwitchButton handleChange={handleChange} checked={isToggle}/>

    </div>
);
  • Related