Skip to content

How do I return an observable from a computed? #3953

Answered by mweststrate
ofersadgat asked this question in Q&A
Discussion options

You must be logged in to vote

computeds are supposed to be side effect free, which your example clearly isn't, as the whole point of it is to make a side effect. Instead, set up a reaction in the constructor (or on the first read of a not computed getter), that reacts to your input URL and initiates the fetch, and stores the result in a local observable. Something like reaction(() => this.url, url => fetch(url).then(value => Object.assign(this.value, { resolved:true, value })

Please note that this setup is still suspectable to synchronization issues, so you probably want to make sure that it was the latest fetch you issued that is currently resolving, before updating this.value.

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
3 replies
@ofersadgat
Comment options

@mweststrate
Comment options

@ofersadgat
Comment options

Answer selected by ofersadgat
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants