How to Post RGB Data in React?

Viewed 17

Currently, I'm making a system that can control home electrical equipment on the web. Backend is ready, It implements RGB picker for the light.

However, I got error. enter image description here

POST xxx.com/turn_on 422

When I choose a color, I can see those variables in the console

   const red = rgb_color["red"]
   const green = rgb_color["green"]
   const blue = rgb_color["blue"]

so variables are nothing problem I guess. I guess this section is not good but I don't know hot fix it.

      {
        entity_id: entity_id, 
        rgb_color: [red, green, blue],
        brightness: brightness_value
      },

By the way, I can get through it in Postman. enter image description here

This is Whole code

LightDetailCondo.js

import React, { useState, useEffect, useCallback, onClick} from 'react';
import axios from 'axios';

import ic_light from "../../images/icons/ic_light.png"

import hexRgb from 'hex-rgb';

const cookies = new Cookies();

const LightDetailCondo = () => {
  const history = useHistory();

  const [light, setLight] = useState([]);

  const { entity_id } = useParams();

  const [brightness_value, setBrightnessValue] = useState();
  const [hex_value, setHexValue] = useState();

  const rgb_color = hexRgb(hex_value);

  const red = rgb_color["red"]
  const green = rgb_color["green"]
  const blue = rgb_color["blue"]


  const handleSliderChange = (e) => {
    lightOn(e.target.value)
    setBrightnessValue(e.target.value)
  }

  const lightOn = async(data) => {
    await axios.post('xxx.com/turn_on',
      {
        entity_id: entity_id, 
        rgb_color: [red, green, blue],
        brightness: brightness_value
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${cookies.get('accesstoken')}`
        },
      })
      .then(result => {
        console.log('Turn on!');
        getDevices();
      })
      .catch(err => {
        console.log(err);
        console.log('Turn on Missed!');
      });
  }

const getDevices = async(data) => {
  await axios.get('xxx.com/device_list',
    {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${cookies.get('accesstoken')}`
      },
    })
    .then(result => {
      console.log(result.data)
      setLight(result.data.attributes.light);  
    })
    .catch(err => {
      console.log(err);
    });
}

useEffect(() => {
  getDevices();
    }, []);

console.log(light)
console.log(brightness_value)
console.log(rgb_color)
console.log(rgb_color["red"])
console.log(rgb_color["green"])
console.log(rgb_color["blue"])
console.log(hex_value)


  return (
    <div className="container">
      <div className="row mx-auto text-center">
          <>
            {light.filter(c => c.entity_id === entity_id).map((item,i) => 
              <div key={i} className="col-12">
                <div className="box h-100">
                <p>{item.room_name}</p>
                <p>{item.entity_id}</p>
                <p>{item.brightness}</p>
                <img className="" src={ic_light_off} />
                <input type="range" name="speed" min="0" max="100" 
                value={brightness_value} onChange={handleSliderChange}></input><br></br>
                <input type="color" name="favorite_color"
                onChange={handleSliderChange}></input>
                <br></br>
                <Link to={`/discover_condo`} className='btn btn-primary col-4'>Back</Link>
                </div>
              </div>
            )}

          </>
      </div>
    </div>
  );
}
export default LightDetailCondo;
1 Answers

Have you tried logging the bod of your post request before sending it ? I think it might help us understand what's going ons as an error 422 means that the server understands the content type of the request entity, and the syntax of the request entity is correct.

const lightOn = async(data) => {
console.log("Body sent to server", {
    entity_id: entity_id, 
    rgb_color: [red, green, blue],
    brightness: brightness_value
  })
await axios.post('xxx.com/turn_on',
  {
    entity_id: entity_id, 
    rgb_color: [red, green, blue],
    brightness: brightness_value
  },
  {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${cookies.get('accesstoken')}`
    },
  })
  .then(result => {
    console.log('Turn on!');
    getDevices();
  })
  .catch(err => {
    console.log(err);
    console.log('Turn on Missed!');
  });

}

Related