mobx: Triggering a fetch within a @computed value
Doing side-effects inside computed values is not encouraged, but it can be useful sometimes:
class BookStore {
@observable _books = null;
@computed get books() {
if (this._books == null) {
this.fetchBooksFromServer();
}
return this._books;
}
fetchBooksFromServer() {
// Make an API request then call `this.booksLoaded` with the response
}
@action booksLoaded(response) {
// Update the list `this._books`
}
}
export default new BookStore();
The above design makes it simple to only fetch the data that the current UI needs. As soon as a React component references BookStore.books, the store will automatically fetch the list of books from the server. If it’s not referenced by any component, books won’t be fetched.
I’m curious to know your thoughts about this, and how you design fetching mechanisms such that it only fetches what the UI needs.
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Comments: 27 (3 by maintainers)
@mweststrate re: future ideas like onBecomeObserved, perhaps that’s a good idea… But, just something to keep in mind as mobx evolves and gains adoption is to be careful and picky about any APIs you introduce over time, otherwise it will become bloatware. I don’t believe every issue calls for a new feature, it may require a refactor/rethink or just patterns for how to use existing features. Just wanted to remind you about that or you’ll run into a bad situation of API bloat.
Yes I actually think this is a really useful pattern indeed, and although it has side effects, I think this has the intended behavior. I have seen other people doing similar things with great success.
In the future I want to add the option to add hooks to be notified when an observable becomes (un)used, so that you could do something like:
@mweststrate I know this is a fairly old issue but do you still stand by your first comment in this thread that putting the fetch in computed is an acceptable approach, or is there a new method that you would recommend?
Without going into a ton of detail I usually do this with a few pieces
Actions that update criteria will transparently cause the any computeds derived from the response to be updated without knowing there was an async call in the middle.