Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

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

Awesome Lists containing this project

README

        






React MobX async


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.