Recently, I came across Immutable JS and was intrigued by its potential to reduce bugs caused by accidental mutations. The library also offers performance optimizations, but I'm struggling to grasp how to manage state within a module.
For instance, in a scenario where I have a socket.io server supporting multiple streams, I typically use two global variables within the module to track connected clients and available streams:
var clients = []
var streams = []
If a user connects, I can easily update the client state using .push
in the io.on("connection")
event handler knowing that the new socket is added.
With Immutable JS, my module's object structure now looks like this:
var state = Immutable.Map({
clients : Immutable.List.of(),
streams : Immutable.List.of()
})
But inside the socket io connection handler, I'm unsure about updating the global state. It seems challenging to maintain application state with Immutable JS as I currently understand it.
// Define the Immutable array, remains constant throughout the application
var state = Immutable.Map({
clients : Immutable.List.of(),
streams : Immutable.List.of()
})
io.on("connection", (socket) => {
console.log(state.clients)
// Attempting to update the state of clients here leads to issues
// as changes are local within the current scope
var clientsArray = state.clients
clientsArray.push(socket)
state.set("clients", clientsArray)
console.log(state.clients)
})
Based on my understanding, I anticipate the following output when two clients connect:
// First client connects
[]
[ { socket object } ]
// Second client connects
[]
[ { socket object } ]
Is there a way to update the object to achieve this instead?
[ { socket object }, { socket object } ]
Or should I resort to using mutable global state? This dilemma arises because methods in React allow updating component state and using the new state elsewhere in the component.