首页 > 解决方案 > How to implement side effect on observable property?

问题描述

I relativly new in Mobx and I need automaticaly call a function when this observable array is update. The observable array :

 @observable Todos = []

I've many function to manage this array (addToso, removeTodo, ...) and I would like to avoid having to call this function in each of the functions that update this array.

For exemple :

@action addTodo(todo, important) {
  const newTodo = {
   id : Math.random(), 
   text : todo,
   isImportant : important,
   completed : false,
   date : Date.now()
  }
  this.Todos.push(newTodo)
}

I want when Todos is update a function automaticaly run for save Todos in my database.

const UpdateDbData = (id, newTodos) => {
 firebase.database().ref(`users/${id}`).update({
   todos : newTodos
 })
.catch(error => console.log(error))
}

Here newTodo is for the current value of the Todos array (id for the user id)

I've test with autorun and reaction but I dont understand how use them properly.

How can do that ?

标签: javascriptreactjsmobxmobx-react

解决方案


我更喜欢这种mobx.observe方法:https ://mobx.js.org/refguide/observe.html#observe 。

你可以使用它:

constructor(){
  mobx.observe(this.Todos, (change) => {
   // update your backend data here.
   doSomething(this.Todos);
  })
}

此方法仅在 todos 数组更改时触发。不在任何其他正在更改的属性上。

笔记:

  • 您可以提取该方法,以便您可以轻松地使其在不同的属性上执行(只需在其他属性上使用 mobx.observe)
  • 如果有很多更改,您可以将方法包装在 debounce 方法中
  • 如果你观察到两次方法会被触发两次,所以去抖动很方便!
  • 每个(事务)操作只调用一次观察方法。(就像自动运行一样)。

推荐阅读