Last active
August 7, 2019 11:05
-
-
Save mweststrate/5dc06424146770409d4d5c850f15a5ca to your computer and use it in GitHub Desktop.
City.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { decorate, observable, flow, onBecomeObserved, onBecomeUnobserved } from 'mobx' | |
import { log } from './log' | |
const APPID = '<secret>' | |
export class City { | |
location | |
temperature | |
interval | |
constructor(location) { | |
this.location = location | |
// only start data fetching if the temperature property is actually used! | |
onBecomeObserved(this, 'temperature', this.resume) | |
onBecomeUnobserved(this, 'temperature', this.suspend) | |
} | |
resume = () => { | |
log(`Resuming ${this.location}`) | |
this.interval = setInterval( | |
() => this.fetchTemperature(), | |
5000 | |
) | |
} | |
suspend = () => { | |
log(`Suspending ${this.location}`) | |
this.temperature = undefined | |
clearInterval(this.interval) | |
} | |
// An async flow | |
// Note that it works just like async / await, but with different syntax | |
fetchTemperature = flow(function*() { | |
const res = yield window.fetch( | |
`https://api.openweathermap.org/data/2.5/weather?appid=${APPID}&q=${this.location}` | |
) | |
const json = yield res.json() | |
try { | |
this.temperature = Math.round(json.main.temp - 273.15) | |
log(`Temperature in ${this.location}: ${this.temperature}`) | |
} catch (e) { | |
log(`Failed to fetch temperature: ${e}`) | |
} | |
}) | |
} | |
// Decorate without decorate syntax | |
decorate(City, { | |
location: observable, | |
temperature: observable | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment