-1

I want to trigger a function whenever a new ImmutableJS object is created. I want to use an ImmutableJS object as my React application state and I want to reduce boilerplate code.

Here's part of what I have now:

function addTodo(text) {
  let state = store.getState(); // Gets ImmutableJS object.
  let todos = state.get('todos');
  let newState = state.set('todos', todos.push('text'));
  store.update(newState); // Triggers rerender.
}

Here's what I want it to be like:

function addTodo(text) {
  let state = store.getState(); // Gets ImmutableJS object.
  state.get('todos').push(text); // Store listens to change and replaces the current state with the newly created state. Store automatically triggers rerender.
}

Is this possible?

I tried wrapping the entire addTodo in withMutations, but withMutations allows only shallow mutations.

Leo Jiang
  • 24,497
  • 49
  • 154
  • 284
  • Isn’t the point with immutableJS that you don’t want to use mutable objects? How about adding a higher order function if you want to reduce boilerplate code? – David Hellsing Oct 10 '16 at 08:40
  • I want it to be immutable for `shouldUpdateComponent`. How would higher order functions help in this case? You mean pass in state to `addTodo` as an argument and return the new state? I could be updating the state multiple times in one function and I'd still have to call `state.set` multiple times. – Leo Jiang Oct 10 '16 at 08:56
  • 1
    look at https://github.com/reactjs/redux to handle reactjs app state and then store state as immutable objects for faster `shouldUpdateComponent`. I done several projects with this already. Redux will handle notifications to your components about change in state. – Lukas Liesis Oct 11 '16 at 08:58

1 Answers1

1

Agree with Lukas' comment. This is really what Redux is for. You mutate the state of your stores and it will force a re-render of your component tree(s) with the new values.
I'm not aware of any sort of observable functions in Immutable.js itself, there might be a third part library that has that functionality though.

rooftop
  • 3,031
  • 1
  • 22
  • 33
  • Redux reducers are just ImmutableJS methods. State (current ImmutableJS object) + action (ImmutableJS method name and arguments) -> new state (new ImmutableJS object). I'm currently playing around with Cortex and Baobab. – Leo Jiang Oct 19 '16 at 23:16