Для корректной записи асинхронных данных можно использовать два пути.
Cделать обычный mobx
метод, передать ему полученные данные. Он их запишет в стейт
loadWeather = city => {
fetch(
'https://abnormal-weather-api.herokuapp.com/cities/search?city=' + city
)
.then(response => response.json())
.then(data => {
this.setWeatherData(data);
});
};
setWeatherData = data => {
this.weatherData = data;
};
Использовать runInAction()
import { runInAction } from "mobx";
// ...
loadWeatherRunInThen = city => {
fetch('https://abnormal-weather-api.herokuapp.com/cities/search?city=' + city)
.then(response => response.json())
.then(data => {
runInAction(() => {
this.weatherData = data;
});
});
};
Есть даже третий вариант! Использовать flow
от mobx
.
import { flow } from 'mobx'
const apiUrl = 'http://dummy.restapiexample.com/api/v1/employees'
class EmployeeService {
getEmployees = () => {
return fetch(apiUrl).then((response) => response.json())
}
getEmployeesAsyncAwait = async () => {
const response = await fetch(apiUrl)
const data = await response.json()
return data
}
getEmployeesGenerator = flow(function* () {
const response = yield fetch(apiUrl)
const data = yield response.json()
return data
})
}
export default EmployeeService