skip to Main Content

In the Data of the API document below,

If "brightness_value" is larger than 0,
I want to set mode to "turn_on".

If brightness_value is 0,
I want to set mode to "turn_off".

Is that possible to implement?

If so, how?

API Document

Method: POST
URL: xxx.com
Data:

{
"time_start":"16:20",
"time_end":"16:21",
    "mode":{
        "mode":"turn_off", //or “turn_on”
        "rgb_color":[255,255,255],
        "brightness":50
    }
}

My React.js code

  const [brightness_value, setBrightnessValue] = useState();

  const setSchedule = async(data) => {
    await axios.post('xxx.com',
      {
        time_start: "16:20",
        time_end: "16:21",
        mode: {
          mode: "turn_off", 
          rgb_color: [255,255,255], 
          brightness: brightness_value,
        }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${cookies.get('accesstoken')}`
        },
      })
      .then(result => {
        console.log('Scheduled!');   
      })
      .catch(err => {
        console.log(err);
        console.log('Missed Schedule!');
      });
  }

2

Answers


  1. Use the ternary operator for this:

    mode: {
             mode: brightness_value === 0 ? "turn_off":"turn_on",  
              rgb_color: [255,255,255], 
              brightness: brightness_value,
            }
    
    Login or Signup to reply.
  2. mode: {
             mode: Number.parseInt(brightness_value) === 0 ? "turn_off":"turn_on",  
              rgb_color: [255,255,255], 
              brightness: brightness_value,
            }
    

    It should do the job.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search