Home > other >  How to call function in a different component in React.js?
How to call function in a different component in React.js?

Time:01-23

I have two components.

DropDownForRoomChangeCondo.js js that displays radio buttons. DiscoverCondoRoom.js displays DropDownForRoomChangeCondo.js.

enter image description here

What I want to achieve is In DropDownForRoomChangeCondo.js, When sending a request to the backend with handleChange (when switching the radio button) I want to change the screen display by calling getDevices(); in DiscoverCondoRoom.js. (Since the assignment of the room where the device is installed changes when the radio button is switched, I want to update the display)

Issue/error message

Currently, when sending a request to the backend with handleChange (when switching the radio button) Display update does not occur.

DropDownForRoomChangeCondo.js

import Dropdown from 'react-bootstrap/Dropdown';

const DropDownForRoomChangeCondo = (item) => {
  const history = useHistory();
  const [devices, setDevices] = useState([]);

  const handleChange = e => {
    setVal(e.target.name);
    setDeviceRoomName(e.target.name);
  }


  const setDeviceRoomName = async(data) => {
    console.log("Body sent to server", {
      attributes: 
      [
        {
          entity_id : item.item.entity_id, 
          room_name: data
        }
    ]
    })
    await axios.post('xxx.com',
      {
          attributes: 
          [
            {
              entity_id : item.item.entity_id, 
              room_name: data
            }
        ]
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${cookies.get('accesstoken')}`
        },
      })
      .then(result => {
        console.log('Set Device Room Name!');
        getDevices();
      })
      .catch(err => {
        console.log(err);
        console.log('Missed Set Device Room Name!');
      });
  }

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


  const keys = [
    "camera",
    "climate",
    "cover",
    "light",
    "lock",
    "sensor",
    "switch",
  ];

  const entities = keys
    .map((key) => (devices[key] || []).map((e) => ({ ...e, key })))
    .flat();

  const roomNames = [...new Set(entities.map((entity) => entity.room_name))];


  const [val, setVal] = useState(item.item.room_name);
  console.log(val)
  console.log(typeof(val))


  const CustomToggle = React.forwardRef(({ children, onClick }, ref) => (
    <a
    href=""
    ref={ref}
    onClick={(e) => {
      e.preventDefault();
      onClick(e);
    }}
  >
    {children}
    <img className="ic_edit" src={ic_edit} />
  </a>
  ));

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


  return (
    <>

                    <div className="">
                    <p>{item.item.room_name}</p>
                    <Dropdown className="room_change_dropdown_top">

                    <Dropdown.Toggle as={CustomToggle} id="dropdown-custom-components" />

                    <Dropdown.Menu className="room_change_dropdown">
                        <Dropdown.Item className="room_change_dropdown_item">
                          {roomNames.map((room_names, i) => (
                            <div className="flex_radio">
                              <input
                                className="room_change_radio"
                                type="radio"
                                value={room_names}
                                name={room_names}
                                onChange={handleChange}
                                checked={val === room_names}
                              />
                              <p className="drop_down_p">{room_names}</p>
                            </div>
                            ))}
                        </Dropdown.Item>
                      </Dropdown.Menu>
                    </Dropdown>
                    </div>

    </>
  );
}
export default DropDownForRoomChangeCondo;

DiscoverCondoRoom.js

const DiscoverCondoRoom = () => {
  const history = useHistory();
  const [devices, setDevices] = useState([]);

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

  const lll = Object.keys(devices);
  const object_device_value = Object.values(devices).flat();



  const keys = [
    "camera",
    "climate",
    "cover",
    "light",
    "lock",
    "sensor",
    "switch",
  ];

  const entities = keys
    .map((key) => (devices[key] || []).map((e) => ({ ...e, key })))
    .flat();

  const roomNames = [...new Set(entities.map((entity) => entity.room_name))];



  return (
    <>
        <div className="container condo_container">
                    {entities.map((entity, i) => (
                            <DropDownForRoomChangeCondo item={entity} />
                    ))}
        </div>
    </>
  );
}
};


export default DiscoverCondoRoom;

CodePudding user response:

You need to pass your getDevices Method as a prop to your dropdown component.

<DropDownForRoomChangeCondo item={entity} getDevices={getDevices} />

Then inside your DropDown Component, call the getDevices Method at your desired place by calling props.getDevices().

Also, i would suggest to define props like so:

    const DropDownForRoomChangeCondo = (props) => {
  const history = useHistory();
  const [devices, setDevices] = useState([]);
…

And then access item by pointing to props.item

  • Related