I have a state called this.state.devices
which is an array of device
objects.
Say I have a function
updateSomething: function (device) {
var devices = this.state.devices;
var index = devices.map(function(d){
return d.id;
}).indexOf(device.id);
if (index !== -1) {
// do some stuff with device
devices[index] = device;
this.setState({devices:devices});
}
}
Problem here is that every time this.updateSomething
is called, the entire array is updated, and so the entire DOM gets re-rendered. In my situation, this causes the browser to freeze as I am calling this function pretty every second, and there are many device
objects. However, on every call, only one or two of these devices are actually updated.
What are my options?
EDIT
In my exact situation, a device
is an object that is defined as follows:
function Device(device) {
this.id = device.id;
// And other properties included
}
So each item in the array of state.devices
is a specific instant of this Device
, i.e. somewhere I'd have:
addDevice: function (device) {
var newDevice = new Device(device);
this.setState({devices: this.state.devices.push(device)});
}
My updated answer how on to updateSomething
, I have:
updateSomething: function (device) {
var devices = this.state.devices;
var index = devices.map(function(d){
return d.id;
}).indexOf(device.id);
if (index !== -1) {
// do some stuff with device
var updatedDevices = update(devices[index], {someField: {$set: device.someField}});
this.setState(updatedDevices);
}
}
Problem now is that I get an error that says cannot read the undefined value of id
, and it is coming from the function Device()
; it seems that a new new Device()
is being called and the device
is not passed to it.