Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/silvestrevivo/react-mobx-async
Explanation of different approaches in MobX about async/await for fetching data
https://github.com/silvestrevivo/react-mobx-async
async-await fetch-api mobx observable parceljs reactjs webapp
Last synced: 11 days ago
JSON representation
Explanation of different approaches in MobX about async/await for fetching data
- Host: GitHub
- URL: https://github.com/silvestrevivo/react-mobx-async
- Owner: silvestrevivo
- Created: 2018-07-16T13:55:12.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2018-07-16T21:33:55.000Z (over 6 years ago)
- Last Synced: 2024-11-25T19:35:53.712Z (2 months ago)
- Topics: async-await, fetch-api, mobx, observable, parceljs, reactjs, webapp
- Language: JavaScript
- Size: 16.6 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
Explanation of different approaches in MobX about async/await for fetching data. A first very simple version would be something like this:
```javascript
import { action, observable } from 'mobx'class WeatherStore {
@observable weatherData = {};@action loaderWeather = (city) => {
fetch(`https://abnormal-weather-api.herokuapp.com/cities/search?city=${city}`)
.then(response => response.json())
.then(data => {
this.weatherData = data
console.log('data', data)
})
}
}var store = new WeatherStore()
export default store
```
In MobX4, when we use __enforceActions: true__ we have to take out the change of
the _observable_ from the promise's callback:```javascript
class WeatherStore {
@observable weatherData = {};@action loaderWeather = (city) => {
fetch(`https://abnormal-weather-api.herokuapp.com/cities/search?city=${city}`)
.then(response => response.json())
.then(data => {
this.setWeather(data)
console.log('data', data)
})
}setWeather = data => {
this.weatherData = data
}
}
```Other solution will be using runInAction() inside of the promises:
```javascript
class WeatherStore {
@observable weatherData = {};@action loaderWeather = (city) => {
fetch(`https://abnormal-weather-api.herokuapp.com/cities/search?city=${city}`)
.then(response => response.json())
.then(data => {
runInAction(() => {
this.weatherData = data
console.log('data', data)
})
})
}
}
```
But the best option is running __generators__ to control de _async/await_ flow
of the data fetching:```javascript
import {
configure,
observable,
flow } from 'mobx'configure({enforceActions: true})
class WeatherStore {
@observable weatherData = {};loadWeatherGenerator = flow(function * (city) {
const response = yield fetch(
`https://abnormal-weather-api.herokuapp.com/cities/search?city=${city}`
)
const data = yield response.json()
this.weatherData = data
console.log('data', data)
});
}var store = new WeatherStore()
export default store
```Here inside is possile to use __try/catch__ combined with __axios__ to catch data.