项目作者: jeffijoe

项目描述 :
Makes async function state management in MobX fun.
高级语言: TypeScript
项目地址: git://github.com/jeffijoe/mobx-task.git
创建时间: 2017-02-22T21:58:07Z
项目社区:https://github.com/jeffijoe/mobx-task

开源协议:MIT License

下载


mobx-task

npm
CI
Coveralls
npm
npm

Takes the suck out of managing state for async functions in MobX.

Table of Contents

Installation

  1. npm install --save mobx-task

What is it?

mobx-task removes the boilerplate of maintaining loading and error state of async functions in MobX.

Your code before:

  1. class TodoStore {
  2. @observable fetchTodosRunning = true
  3. @observable fetchTodosError
  4. async fetchTodos () {
  5. try {
  6. runInAction(() => {
  7. this.fetchTodosRunning = true
  8. })
  9. // ...
  10. await fetch('/todos')
  11. } catch (err) {
  12. runInAction(() => {
  13. this.fetchTodosError = err
  14. })
  15. throw err
  16. } finally {
  17. runInAction(() => {
  18. this.fetchTodosRunning = false
  19. })
  20. }
  21. }
  22. }

Your code with mobx-task

  1. import { task } from 'mobx-task'
  2. class TodoStore {
  3. @task async fetchTodos () {
  4. await fetch('/todos')
  5. }
  6. }

Full example with classes and decorators

  1. import { observable, action } from 'mobx'
  2. import { task } from 'mobx-task'
  3. import React from 'react'
  4. import { observer } from 'mobx-react'
  5. class TodoStore {
  6. @observable todos = []
  7. @task async fetchTodos () {
  8. await fetch('/todos')
  9. .then(r => r.json())
  10. .then(action(todos => this.todos.replace(todos)))
  11. }
  12. }
  13. const store = new TodoStore()
  14. // Start the task.
  15. store.fetchTodos()
  16. // and reload every 3 seconds, just cause..
  17. setInterval(() => {
  18. store.fetchTodos()
  19. }, 3000)
  20. const App = observer(() => {
  21. return (
  22. <div>
  23. {store.fetchTodos.match({
  24. pending: () => <div>Loading, please wait..</div>,
  25. rejected: (err) => <div>Error: {err.message}</div>,
  26. resolved: () => (
  27. <ul>
  28. {store.todos.map(todo =>
  29. <div>{todo.text}</div>
  30. )}
  31. </ul>
  32. )
  33. })}
  34. </div>
  35. )
  36. })

Full example with plain observables

  1. import { observable, action } from 'mobx'
  2. import { task } from 'mobx-task'
  3. import React from 'react'
  4. import { observer } from 'mobx-react'
  5. const store = observable({
  6. todos: [],
  7. fetchTodos: task(async () => {
  8. await fetch('/todos')
  9. .then(r => r.json())
  10. .then(action(todos => store.todos.replace(todos)))
  11. })
  12. })
  13. // Start the task.
  14. store.fetchTodos()
  15. // and reload every 3 seconds, just cause..
  16. setInterval(() => {
  17. store.fetchTodos()
  18. }, 3000)
  19. const App = observer(() => {
  20. return (
  21. <div>
  22. {store.fetchTodos.match({
  23. pending: () => <div>Loading, please wait..</div>,
  24. rejected: (err) => <div>Error: {err.message}</div>,
  25. resolved: () => (
  26. <ul>
  27. {store.todos.map(todo =>
  28. <div>{todo.text}</div>
  29. )}
  30. </ul>
  31. )
  32. })}
  33. </div>
  34. )
  35. })

How does it work?

mobx-task wraps the given function in another function which
does the state maintenance for you using MobX observables and computeds.
It also exposes the state on the function.

  1. const func = task(() => 42)
  2. // The default state is `pending`.
  3. console.log(func.state) // pending
  4. console.log(func.pending) // true
  5. // Tasks are always async.
  6. func().then((result) => {
  7. console.log(func.state) // resolved
  8. console.log(func.resolved) // true
  9. console.log(func.pending) // false
  10. console.log(result) // 42
  11. // The latest result is also stored.
  12. console.log(func.result) // 42
  13. })

It also maintains error state.

  1. const func = task(() => {
  2. throw new Error('Nope')
  3. })
  4. func().catch(err => {
  5. console.log(func.state) // rejected
  6. console.log(func.rejected) // true
  7. console.log(err) // Error('Nope')
  8. console.log(func.error) // Error('Nope')
  9. })

And it’s fully reactive.

  1. import { autorun } from 'mobx'
  2. const func = task(async () => {
  3. return await fetch('/api/todos').then(r => r.json())
  4. })
  5. autorun(() => {
  6. // Very useful for functional goodness (like React components)
  7. const message = func.match({
  8. pending: () => 'Loading todos...',
  9. rejected: (err) => `Error: ${err.message}`,
  10. resolved: (todos) => `Got ${todos.length} todos`
  11. })
  12. console.log(message)
  13. })
  14. // start!
  15. func().then(todos => { /*...*/ })

Task Groups

since mobx-task v2.0.0

A TaskGroup is useful when you want to track pending, resolved and rejected state for multiple tasks but treat them as one.

Under the hood, a TaskGroup reacts to the start of any of the tasks (when pending flips to true), tracks the latest started task, and proxies all getters
to it. The first pending task (or the first task in the input array, if none are pending) is used as the initial task to proxy to.

IMPORTANT: Running the tasks concurrently will lead to wonky results. The intended use is for
tracking pending, resolved and rejected states of the last run task. You should prevent your users from
concurrently running tasks in the group.

  1. import { task, TaskGroup } from 'mobx-task'
  2. const toggleTodo = task.resolved((id) => api.toggleTodo(id))
  3. const deleteTodo = task.resolved((id) => { throw new Error('deleting todos is for quitters') })
  4. const actions = TaskGroup([
  5. toggleTodo,
  6. deleteTodo
  7. ])
  8. autorun(() => {
  9. const whatsGoingOn = actions.match({
  10. pending: () => 'Todo is being worked on',
  11. resolved: () => 'Todo is ready to be worked on',
  12. rejected: (err) => `Something failed on the todo: ${err.message}`
  13. })
  14. console.log(whatsGoingOn)
  15. })
  16. // initial log from autorun setup
  17. // <- Todo is ready to be worked on
  18. await toggleTodo('some-id')
  19. // <- Todo is being worked on
  20. // ...
  21. // <- Todo is ready to be worked on
  22. await deleteTodo('some-id')
  23. // <- Todo is being worked on
  24. // ...
  25. // <- Something failed on the todo: deleting todos is for quitters

API documentation

There’s only a single exported member; task.

ES6:

  1. import { task } from 'mobx-task'

CommonJS:

  1. const { task } = require('mobx-task')

The task factory

The top-level task creates a new task function and initializes it’s state.

  1. const myAwesomeFunc = task(async () => {
  2. return await doAsyncWork()
  3. })
  4. // Initial state is `pending`
  5. console.log(myAwesomeFunc.state) // "pending"

Let’s try to run it

  1. const promise = myAwesomeFunc()
  2. console.log(myAwesomeFunc.state) // "pending"
  3. promise.then((result) => {
  4. console.log('nice', result)
  5. console.log(myAwesomeFunc.state) // "resolved"
  6. })

Parameters:

  • fn - the function to wrap in a task.
  • opts - options object. All options are optional.
    • opts.state - the initial state, default is 'pending'.
    • opts.error - initial error object to set.
    • opts.result - initial result to set.
    • opts.swallow - if true, does not throw errors after catching them.

Additionally, the top-level task export has shortcuts for the opts.state option (except pending, since its the default).

  • task.resolved(func, opts)
  • task.rejected(func, opts)

For example:

  1. const func = task.resolved(() => 42)
  2. console.log(func.state) // resolved

Is the same as doing:

  1. const func = task(() => 42, { state: 'resolved' })
  2. console.log(func.state) // resolved

As a decorator

The task function also works as a decorator.

Note: you need to add babel-plugin-transform-decorators-legacy to your babel config for this to work.

Example:

  1. class Test {
  2. @task async load () {
  3. }
  4. // shortcuts, too
  5. @task.resolved async save () {
  6. }
  7. // with options
  8. @task({ swallow: true }) async dontCareIfIThrow() {
  9. }
  10. // options for shortcuts
  11. @task.rejected({ error: 'too dangerous lol' }) async whyEvenBother () {
  12. }
  13. }

The task itself

The thing that task() returns is the wrapped function including all that extra goodness.

state

An observable string maintained while running the task.

Possible values:

  • "pending" - waiting to complete or didn’t start yet (default)
  • "resolved" - done
  • "rejected" - failed

pending, resolved, rejected

Computed shorthands for state. E.g. pending = state === 'pending'

result

Set after the task completes. If the task fails, it is set to undefined.

args

An array of arguments that were used when the task function was invoked last.

error

Set if the task fails. If the task succeeds, it is set to undefined.

match()

Utility for pattern matching on the state.

Example:

  1. const func = task((arg1, arg2, arg3, ..asManyAsYouWant) => 42)
  2. const result = func.match({
  3. pending: (arg1, arg2, arg3, ...asManyAsYouWant) => 'working on it',
  4. rejected: (err) => 'failed: ' + err.message,
  5. resolved: (answer) => `The answer to the universe and everything: ${answer}`
  6. })

wrap()

Used to wrap the task in another function while preserving access to the state - aka. Higher Order Functions.

Returns the new function, does not modify the original function.

  1. // Some higher-order-function...
  2. const addLogging = function (inner) {
  3. return function wrapped () {
  4. console.log('Started')
  5. return inner.apply(this, arguments).then(result => {
  6. console.log('Done!')
  7. return result
  8. })
  9. }
  10. }
  11. const func = task(() => 42)
  12. const funcWithLogging = func.wrap(addLogging)

setState()

Lets you set the internal state at any time for whatever reason you may have. Used internally as well.

Example:

  1. const func = task(() => 42)
  2. func.setState({ state: 'resolved', result: 1337 })
  3. console.log(func.state) // 'resolved'
  4. console.log(func.resolved) // true
  5. console.log(func.result) // 1337

bind()

The wrapped function patches bind() so the bound function contains the task state, too.
Other than that it functions exactly like Function.prototype.bind.

  1. const obj = {
  2. value: 42,
  3. doStuff: task(() => this.value)
  4. }
  5. const bound = obj.doStuff.bind(obj)
  6. bound()
  7. console.log(bound.pending) // true

reset()

Resets the state to what it was when the task was initialized.

This means if you use const t = task.resolved(fn), calling t.reset() will set the state to resolved.

TaskGroup

Creates a TaskGroup. Takes an array of tasks to track. Implements the readable parts of the Task.

Uses the first task in the array as the proxy target.

  1. import { task, TaskGroup } from 'mobx-task'
  2. const task1 = task(() => 42)
  3. const task2 = task(() => 1337)
  4. const group = TaskGroup([
  5. task1,
  6. task2
  7. ])
  8. console.log(group.state)
  9. console.log(group.resolved)
  10. console.log(group.result)

Gotchas

Wrapping the task function

It’s important to remember that if you wrap the task in something else, you will loose the state.

Bad:

  1. import once from 'lodash/once'
  2. const func = task(() => 42)
  3. const funcOnce = once(func)
  4. console.log(funcOnce.pending) // undefined

This is nothing special, but it’s a common gotcha when you like to compose your functions. We can make this work though,
by using .wrap(fn => once(fn)). See the wrap() documentation.

Good:

  1. import once from 'lodash/once'
  2. const func = task(() => 42)
  3. const funcOnce = func.wrap(once)
  4. console.log(funcOnce.pending) // true

Using the decorator on React Components

Using the @task decorator on React components is absolutely a valid use case, but if you use React Hot Loader or
any HMR technology that patches functions on components, you will loose access to the task state.

A workaround is to not use the decorator, but a property initializer:

  1. class Awesome extends React.Component {
  2. fetchTodos = task(() => {
  3. return fetch('/api/todos')
  4. })
  5. render () {
  6. return (
  7. <div>
  8. {this.fetchTodos.match(...)}
  9. </div>
  10. )
  11. }
  12. }

Using the decorator with autobind-decorator

Because of the way the autobind-decorator class decorator works, it won’t pick up any @task-decorated
class methods because @task rewrites descriptor.value to descriptor.get which autobind-decorator does
not look for. This is due to the fact that autobind-decorator does not (and should not) evaluate getters.

You can either bind the tasks in the constructor, use field initializers, or apply the @autobind method decorator before the @task decorator. @task @autobind method() {} is the correct order.

  1. import autobind from 'autobind-decorator'
  2. @autobind
  3. class Store {
  4. value = 42
  5. // Using decorator
  6. @task boo () {
  7. return this.value
  8. }
  9. // Using field initializer
  10. woo = task(() => {
  11. return this.value
  12. })
  13. // Decorator with autobind applied first
  14. @task @autobind woohoo () {
  15. return this.value
  16. }
  17. }
  18. // Nay
  19. const store = new Store()
  20. store.boo() // 42
  21. const boo = store.boo
  22. boo() // Error: cannot read property "value" of undefined
  23. // Yay
  24. store.woo() // 42
  25. const woo = store.woo
  26. woo() // 42
  27. const woohoo = store.woohoo
  28. woohoo() // 42

Alternatively, use this.boo = this.boo.bind(this) in the constructor.

Using with typescript

Best way to work with typescript is to install @types/mobx-task. Definitions covers most use cases. The tricky part is decorators because they are not able to change the type of the decorated target. You will have to do type assertion or use plain observables.

  1. npm install --save-dev @types/mobx-task

Example:

  1. class Test {
  2. @task taskClassMethod(arg1: string, arg2: number) {
  3. let result: boolean
  4. ...
  5. return result
  6. }
  7. @task assertTypeHere = <Task<boolean, [string, number]>>((arg1: string, arg2: number) => {
  8. let result: boolean
  9. ...
  10. return result
  11. })
  12. @task assertTypeHereWithAs = ((arg1: string, arg2: number) => {
  13. let result: boolean
  14. ...
  15. return result
  16. }) as Task<boolean, [string, number]>
  17. }
  18. const test = new Test()
  19. // dont care about task methods, props and return value and type
  20. const doSomething = async () => {
  21. await test.taskClassMethod('a', 1)
  22. ...
  23. }
  24. // want to use task props and returned promise
  25. (test.taskClassMethod as Task)("one", 2).then(...) // Task<any, any[]>
  26. const {result} = <Task<Result>>test.taskClassMethod // Task<Result, any[]>
  27. const {args} = test.taskClassMethod as Task<void, [string]>

Author

Jeff Hansen - @Jeffijoe