Add values to temporary state array

You want to use setIn() rather than setValue().

See this post: Using setIn() to change a temp state variable - #3 by MarkR

The first key to setIn() (pun intended) is to make sure you are using your key value correctly. It is the first parameter of setIn(). If it does not exists, it will be appended. If it does exist, it will overwrite the existing key (aka element) which leads to the second important thing: The entire element will get overwritten with the new value. That means if you want to just set a single property, you must recreate the entire object with the changed property and set that.

For example if you have this object at key 1: {myValue: 72, myOtherValue: 'Fred'} and you do setIn([1], {myValue: 23}), the object will now be missing myOtherValue.

I was just doing that today and here is some sample code that loops through all elements in my temp state array, makes some changes and reloads them into the temp state array:

for (let i = 0; i < Timers.value.length; i++) {
  let item = Timers.value[i]
  if (item.paused) {continue}
  item.countDownSeconds = item.countDownSeconds - 1
  if (item.countDownSeconds <= 0 && !sndAlarm[i].playing) {
    console.log("Alarm On")
    sndAlarm[i].play()
  }
  let s = new Date(item.countDownSeconds * 1000).toISOString().substr(11, 8)
  Timers.setIn([i], item )
}

Here's a simpler version to set a single value:

let item = Timers.value[i]
item.paused = true
Timers.setIn([i], item )

The other option is to make an array with all of the values ands then use setValue(myNewArray) at the end.

5 Likes