에러노트

react-native mobx render가 바로바로 되지 않을 경우

thebirghtwide 2021. 8. 4. 00:16

mobx를 사용, 값의 변화가 생겼는데 반응하지 않는 경우

현재 mobx를 통해 api로 실시간 받아온 데이터를 화면에 뿌려주게 앱을 완성하였다. 위 처럼 실시간으로 api로 값을 받아오는 것을 확인하였는데 놀랍게도 화면에는 아무런 반응이 없는 것을 확인했다... 

 

위 처럼 화면에는 아무런 반응이 없다. 분명 무엇인가 잘못되어 있다. 

 

 문제 해결

구글링을 통해 열심히 알아본 결과 

 

https://stackoverflow.com/questions/64654663/mobx-react-native-not-re-rendering

 

MobX + React Native not re-rendering

I am building a password reset with react native and MobX I am having a bit of trouble reseting the error state. I have tried multiple solutions but none seem to be working, the onChangeText for the

stackoverflow.com

위 사이트를 통해서 답을 구할 수 있었다. 현재 코드들이 decorator를 사용하여 개발이 완료 되었는데 현재 mobx 버전이 6이라서 더 이상 동작하지 않았던 것이다. ㅠㅠ 그런것도 모르고 ㅠㅠ

 

해결방법은 아주 간단하다. 일단 기존에 store에서 사용된 decorator를 다 없앤다. 

export class CoinListStore {
  // 추후에 다른 store에서 변수를 가지고 올 수도 있음으로 rootstore를 임시로 만들어 둔다. 
  rootStore;

  @observable 
  list: Coin[] = [];
  @observable 
  error: string | null = null;
  @observable 
  showError: boolean = false;
  @observable 
  loading: boolean = false;

  constructor(root){
    this.rootStore = root 
  }
  
  page: number = 0;
  perPage: number = 20;
  baseCurrency: Currency = "USD";

  @action 
  getNextPage() {
    if (this.loading) return;
    this.page += 1;
    this.getData();
  }

이 코드에서 데코레이터들을 다 없애고 

import { makeAutoObservable  } from "mobx";

export class CoinListStore {
  // 추후에 다른 store에서 변수를 가지고 올 수도 있음으로 rootstore를 임시로 만들어 둔다. 
  rootStore;

  list: Coin[] = [];
  error: string | null = null;
  showError: boolean = false;
  loading: boolean = false;

  constructor(root){
    this.rootStore = root;
    makeAutoObservable(this)
  }
  
  page: number = 0;
  perPage: number = 20;
  baseCurrency: Currency = "USD";

  getNextPage() {
    if (this.loading) return;
    this.page += 1;
    this.getData();
  }

여기서 makeAutoObservable을 import 하여 construtor에 makeAutoObservable(this)를 추가하면 mobx 6버전이 정상적으로 돌아가는 것을 확인 할 수 있다. 이제 정말 잘 동작하는지 보자. 

아... 감동이다 ㅠㅠ 정말이지 잘 동작한다. 이로소 나는 또 하나의 큰산을 넘은 기분이다 ㅠㅠ