mobx-promise
A tiny library that makes working with promises in MobX easy.
Installing
npm install --save mobx-promise
Simply initialize an observable object with data
and promiseState
properties, and return a promise from an action decorated with @bindPromiseTo
as such:
import bindPromiseTo from 'mobx-promise' @observable pizzas = data: promiseState: @ @action { return }
Now when getPizzas()
is called, mobx-promise
will update the promiseState
property of pizzas
with promise's lifecycle events — pending, fulfilled or rejected, and the data
property with the result of promise execution.
Exercising control
If you'd like more control on how the promise results are assigned, or if you wish to avoid using decorators, you can use the bindPromise
function instead of the @bindPromiseTo
decorator.
@action { const pizzaPromise = }
This works similar to bindPromiseTo
, but allows you more freedom to do any of the following:
Assigning a nested property to the observable
@action { const pizzaPromise = }
Using the previous state
@action { const pizzaPromise = // Merge / process current result with the previous one }
Returning a promise
@action {const pizzaPromise = return }
Handling rejection and fulfillment
@action { const pizzaPromise = }
Rendering results
mobx-promise
provides the PromiseState
enum for convenience in comparing results. You can choose to use "fulfilled", "rejected" and "pending" as strings instead if you wish.
import Component from 'react'import PromiseState from 'mobx-promise' { const pizzas = appStore switchpizzaspromiseState case PromiseStatePENDING: return <span> Loading yummy pizzas... </span> case PromiseStateFULFILLED: return <ul> pizzasdata </ul> case PromiseStateREJECTED: return <span> No pizza for you </span> }
API
bindPromise
argument | type |
---|---|
promise | Promise |
bindPromise.to
argument | type |
---|---|
observable | MobX Observable |
selector(newData, oldData) | callback |
@bindPromiseTo
argument | type |
---|---|
observableKey | string |