Llamadas asíncronas en MobX State Tree

Sejas
JS School
Published in
1 min readSep 25, 2018

¿Qué son y como se utilizan las `function *` generators ? ¿Se pueden sustituir por async / await?

Hay dos opciones:

  1. Async/Await o promesas, pero en el callback debemos llamar a otro action auxiliar.
  2. Function generators utilizando flow y sustituyendo los await por yield

Con MobX State Tree (MST), es mejor utilizar function generetors , porque nos permiten mantenernos en el contexto de la action y así evitar la creación de las actions auxiliares.

types
.model({
email: "",
password: "",
userLogged: false
})
.actions( self => ({
login: flow(function*(){
try {
let user = yield firebaseAuth.signInAndRetrieveDataWithEmailAndPassword(self.email, self.password)
self.userLogged = true
} catch (error) {
//catch error
}
})
})
)

Por el contrario, utilizando async await , perdemos el contexto y MobX no puede identificar que el callback se está ejecutando dentro de un action.

Por eso obtenemos este error:

the object is protected and can only be modified by using an action

Doc oficial: Creating asynchronous actions

--

--

Sejas
JS School

Remote Software Engineer & Machine Learning Scientist — Mobile Lead Developer (React Native) @ Woonivers. Writer @ JS School - https://jsschool.es