Home > Enterprise >  I want to send the selected radio input to the backend using onChange in react.js
I want to send the selected radio input to the backend using onChange in react.js

Time:01-10

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 With radio input, I use onChange to change heat, cool, auto, off, etc. to temp_mode_val variable I want to send temp_mode_val to the backend with axios Post

Issue is I can send temp_mode_val but it's empty... I don't know why...

enter image description here

React.js

const DiscoverOffice = () => {
    
    const { entity_id } = useParams();
    
    const SetTemperatureMode = async(data) => {
      console.log("Body sent to server", {
      entity_id: entity_id, 
      operation_mode: temp_mode_val
    })
      await axios.post('xxx.com',
        {
          entity_id: entity_id, 
          operation_mode: temp_mode_val
        },
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${cookies.get('accesstoken')}`
          },
        })
        .then(result => {
          console.log(result.data);
          console.log(entity_id);
          console.log(val);
          console.log('Set Mode!');
          setVal(val);
          // getDevices();
        })
        .catch(err => {
          console.log(err);
          console.log(entity_id);
          console.log('Missed set Mode!');
        });
    }


    const [temp_mode_val, setTemperatureMode2] = useState('off');

    const HeatHandleChange = (e) => {
      setTemperatureMode2(e.target.value);
      SetTemperatureMode(e.target.value);
    }

return (
    

                              <div className="ic_schedule_label flex">
                                <input
                                  className="heat_mode_radio"
                                  type="radio"
                                  value="heat"
                                  onChange={HeatHandleChange}
                                  checked={temp_mode_val === 'heat'}
                                />
                                <p className="radio_text">Heat</p>
                              </div>
                              <div className="ic_schedule_label flex">
                                <input
                                  className="heat_mode_radio"
                                  type="radio"
                                  value="cool"
                                  onChange={() => HeatHandleChange('cool')}
                                  checked={temp_mode_val === 'cool'}
                                />
                                <p className="radio_text">Cool</p>
                              </div>
                              <div className="ic_schedule_label flex">
                                <input
                                  className="heat_mode_radio"
                                  type="radio"
                                  value="auto"
                                  onChange={() => HeatHandleChange('auto')}
                                  checked={temp_mode_val === 'auto'}
                                />
                                <p className="radio_text">Auto</p>
                              </div>
                              <div className="ic_schedule_label flex">
                                <input
                                  className="heat_mode_radio"
                                  type="radio"
                                  value="off"
                                  onChange={() => HeatHandleChange('off')}
                                  checked={temp_mode_val === 'off'}
                                />
                                <p className="radio_text">Off</p>
                              </div>

    
      );
}
export default DiscoverOffice;

CodePudding user response:

Instead of e.target.data just use e Since you passing directly the value as the argument.

if you want to use e.target.data you wll have to pass the event to the nested method call. ex:

onChange={(e) => HeatHandleChange(e)

This way you will get e.target.value

CodePudding user response:

Thanks everyone.

onChange={() => HeatHandleChange('Heat')}

and this works.

const SetTemperatureMode = async(data) => {
  console.log("Body sent to server", {
  entity_id: entity_id, 
  operation_mode: data
})
  await axios.post('xxx.com',
    {
      entity_id: entity_id, 
      operation_mode: data
    },
    {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${cookies.get('accesstoken')}`
      },
    })
    .then(result => {
      console.log(result.data);
      console.log(entity_id);
      // console.log(val);
      console.log('Set Mode!');
      setTemperatureMode2(result.data.attributes.climate.filter(c => c.entity_id === entity_id).map((item,i) =>  item.operation_mode
      )[0]);
      // setVal(val);
      getDevices();
    })
    .catch(err => {
      console.log(err);
      console.log(entity_id);
      console.log('Missed set Mode!');
      alert('Unable to set Mode!');
      getDevices();
    });
}

CodePudding user response:

You're passing a string to the function HeatHandleChange. You could use the e variable directly, or pass the change event instead.

You should set the state before calling your function.

const HeatHandleChange = (e) => {
    SetTemperatureMode(e);
    setTemperatureMode2(e); 
}  

You also could use the passed value instead of your state.

await axios.post('xxx.com',
        {
            entity_id: entity_id,
            operation_mode: data
        },
        {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${cookies.get('accesstoken')}`
            },
        })
        .then(result => {
            console.log(result.data);
            console.log(entity_id);
            console.log(val);
            console.log('Set Mode!');
            setVal(val);
            // getDevices();
        })
        .catch(err => {
            console.log(err);
            console.log(entity_id);
            console.log('Missed set Mode!');
        });
  • Related