Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda