Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

226
Visualizações
How to pass data from async fuction to useState() Flask API + React Frontend

I'm trying to get the state of my hue lights using my API and based on this information render the page ( basically if my lamp is on I want my toggle switch on website to be already toggled once the page loads) Currently I'm trying pass data fetched from my API using async function to the useState()

Here is my code

const LightSwitch = (props) => {

  async function lightState(){
    const response = await httpGet('http://192.168.1.124/get_light_state/id/' + props.id);
    let data = await response
    return data;
  } 

  lightState().then(data => {
    console.log(data.Light);
  }
    )

    const [toggleSwitch, setToggleSwitch] = useState();

My API response is

{
  "Light": false
}

Here is my whole code for reference.

import React, { useState } from "react";
import { Switch } from "antd";
import "./LightSwitch.css";

async function httpGet (url){
  const response = await fetch(url,{method: 'GET'});
  const string = await response.text();
  const json = string === "" ? {} : JSON.parse(string);
  return json;
  
}
const LightSwitch = (props) => {

  async function lightState(){
    const response = await httpGet('http://192.168.1.124/get_light_state/id/' + props.id);
    let data = await response
    return data;
  } 

  lightState().then(data => {
    console.log(data.Light);
  }
    )

    const [toggleSwitch, setToggleSwitch] = useState();

  
  const onChangeSwitch = (checked) => {
    setToggleSwitch(!toggleSwitch);
    if (checked) {
      console.log(props.name + ' on');
      httpGet('http://192.168.1.124/turn_on/id/' + props.id);
    }else{
      console.log(props.name + ' off');
      httpGet('http://192.168.1.124/turn_off/id/'+ props.id);
    }

  };

  return (
    <div>
      <Switch checked={toggleSwitch} onChange={onChangeSwitch}></Switch>
    </div>
  );
};
export default LightSwitch;

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda