React/1. React 기초
mobx - runInAction
pancakemaker
2022. 6. 30. 11:19
runInAction
원래 mobx는 액션 함수 내부에서 promise 작업(async/await)을 한 이후 다시 액션 함수를 만들거나, 외부의 액션 함수(ex: setter)를 호출해야 정상적으로 observable값을 바꿀 수 있으나, runInAction을 사용하면 함수 내부에서 observable값을 바꿀 수 있다.
runInAction 사용 전
loadWeather = city => {
fetch(`https://abnormal-weather-api.herokuapp.com/cities/search?city=${city}`)
.then(response => response.json())
.then(data => {
this.setWeatherData(data); //외부의 action 함수 호출
});
};
@action
setWeatherData = data => {
this.weatherData = data;
};
runInAction 사용 후
loadWeatherRunInThen = city => {
fetch(`https://abnormal-weather-api.herokuapp.com/cities/search?city=${city}`)
.then(response => response.json())
.then(data => {
runInAction(() => {
this.weatherData = data; //별도의 action 함수 생성 없이 진행
});
});
};
출처: https://stackoverflow.com/questions/57271153/mobx-runinaction-usage-why-do-we-need-it