jeffijoe / mobx-task

Makes async function state management in MobX fun.
MIT License
238 stars 6 forks source link

More complicated scenarios #6

Closed thejuan closed 6 years ago

thejuan commented 6 years ago

Love the idea! Trying to think through something like this. However I quickly came across scenarios I couldn't see a solution for with this. Was wondering if you had any thoughts on how the library would be used for the below.

Most of our components will have multiple actions (say load and update)

jeffijoe commented 6 years ago

Well that all depends on the behavior you want. 😄

thejuan commented 6 years ago

Ha! I'm thinking ill use tasks on load actions and edit based actions will just feed errors into the loaded screen. If a load fails the UI will be entirely different.

jeffijoe commented 6 years ago

What I meant is, what do you want to happen? if one task fails, show an error? If one task is loading, show loading indicator?

In that case, you can do that with a few simple computeds. I didnt test this, but should work. 😄

class MyStore {
  tasks = [this.stuff1, this.stuff2]

  @computed get error() {
    return anyError(this.tasks)
  }

  @computed get loading() {
    return anyLoading(this.tasks)
  }

  @task async stuff1() {
    // ...
  }

  @task async stuff2() {
    // ...
  }
}

// Reusable utils

function anyError(tasks) {
  // Return the error for any of the tasks if there is one.
  return tasks.map(x => x.error).find(Boolean)
}

function anyLoading(tasks) {
  // Return true if some tasks are pending.
  return tasks.some(x => x.pending)
}
thejuan commented 6 years ago

Thanks that's a good start!