Keven Wang
Keven Wang

Reputation: 1278

Mobx: create an atomic store update function?

Question about react mobx. (although I think it's general to any react store library) Is there a way to create an atomic store update function, without causing components to render during the store update?

The problem I'm having is this:

// store.js
class Store {
  constructor() {
    extendObservable(this, {
      array: [1, 2],
      i: 1
    },

    get current_element() {
      return this.array[this.i];
    }
  }

  update(array, i) {
    this.array = array;
    this.i = i;
  }
}


component.js
// ...
render() {
  return <div>store.current_element</div>
}

Now when I call store.update([0], 0), I get an error on index out of bound. The reason is that, inside store.update() function, after the first line (this.array = array;) is executed, the component's rendering is triggered. The component is therefore trying to reference index 1 of array [0], which throws an index out of bound error. I want to avoid this, and only trigger component rendering after the entire store.update() function is executed.

How could I achieve that?

Upvotes: 2

Views: 418

Answers (1)

mrbarletta
mrbarletta

Reputation: 922

When you update an observable you have to do it with an action. For example

@action setFirstName = firstName => (this.firstName = firstName);
@action setLastName = lastName => (this.lastName = lastName);

Not a mobx fan though :)

Upvotes: 1

Related Questions