Llamadas asíncronas en MobX State Tree

Sejas
Sejas
Sep 25, 2018 · 1 min read

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

Image for post
Image for post

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

JS School

Sejas

Written by

Sejas

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

JS School

JS School

Vídeos, Tutoriales, Noticias y experiencias de JavaScript. El lenguaje más popular para el desarrollo web. Frontend y FullStack. React, Vue, Angular, NodeJS, ES6 …

Sejas

Written by

Sejas

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

JS School

JS School

Vídeos, Tutoriales, Noticias y experiencias de JavaScript. El lenguaje más popular para el desarrollo web. Frontend y FullStack. React, Vue, Angular, NodeJS, ES6 …

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store