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

Time:12-22

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

CodePudding user response:

Use the ternary operator for this:

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

CodePudding user response:

Just add a condition here

  time_start: "16:20",
        time_end: "16:21",
        mode: {
          mode: brightness_value === 0 ? "turn_off":"turn_on", 
          ....

CodePudding user response:

mode: {
         mode: Number.parseInt(brightness_value) === 0 ? "turn_off":"turn_on",  
          rgb_color: [255,255,255], 
          brightness: brightness_value,
        }

It should do the job.

  • Related