Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!