React State with Stomp

Jan 17, 2024
 — by 
Kris Kratz
 in 

I’m using Stomp within my NextJS app, in otherwords, I’m using Stomp with React. I experienced a problem with setting state between scopes. Here’s what was happening: Stomp received a message, and that triggered a function based on the payload. That function updated an object’s state, but it was resetting it to the state the object had when the Stomp object was created!

What the heck!? Why is the object frozen in time!?

Normally, when I update a object controlled in state. I deep clone it, then I modify the clone, and then I set the state to the new clone. Like this:

const [myList, setMyList] = useState([])

function addToMyList(newItem) {
  const nextList = [...myList]
  nextList.push(newItem)
  setMyList(nextList)
}

To manage variables in React, it’s necessary do that through React’s State management system. This introduces some interesting situations… and by that I mean things can get frustrating.

Using Stomp to send and receive messages creates a separate scope where the messages are received and processed. Using the example above, functions triggered when a Stomp Message is received after myList is updated will not see the changes. Basically, myList will be frozen inside of the Stomp scope and not receive any changes to its state.

So the function above won’t work as expected inside of Stomp’s scope.

However, today I learned that setMyList can provide the current version of myList as a variable! This will keep the code concise in other cases as well.

const [myList, setMyList] = useState([])

function addToMyList(newItem) {
  setMyList( ml => [...ml, newItem])
}

I really like how concise this function is anyway. So I’ll probably set things up like this moving forward to avoid most scope issues even if my program isn’t moving between scopes.