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

174
Visualizações
Dynamically match incoming objects to corresponding state in React

I have maybe thirty pieces of state in my React app representing info on my Node server that's constantly being updated via a websocket. The state on the frontend has the same name as the keys coming from the backend.

My frontend state:

const [value, setvalue] = useState(null);
const [day, setday] = useState(null);
const [price, setprice] = useState(null);
const [asset, setasset] = useState(null);
//etc for thirty items

And the objects being piped in via websocket from my Node server, parsed from JSON:

{
  value: 100,
  day: 'Tuesday'
  price: 5
  asset: 'The Goods'
}

The problem is the objects from the backend come in no particular order or frequency. Sometimes it may be all 30 objects, or just one. Then somehow, I need to send that particular object to it's corresponding state object of the same name. Example: with setvalue or maybe setprice. I've tried storing the set function in a string then calling it, but React doesn't recognize the function.

    useEffect(() => {
        webSocket.current = new WebSocket(URL);
        webSocket.current.onmessage = (message) => {
            const data = JSON.parse(message.data);
              for (let key in data) {
                  const funct = "set" + [key];
                  console.log(funct, key);
                  //this function is not recognized.
                  funct(key);
              }
        };
        return () => webSocket.current.close();
    }, []);

Obviously I could have thirty if statement matching the object to the state, but I'd prefer something more elegant. Thanks!

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