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!