Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to create a condition and post using axios at React.js

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".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!');
      });
  }

>Solution :

Use the ternary operator for this:

mode: {
         mode: brightness_value === 0 ? "turn_off":"turn_on",  
          rgb_color: [255,255,255], 
          brightness: brightness_value,
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading