4. usestore-ts

학습 키워드

  • usestore-ts

  • useSyncExternalStore

usestore-ts 사용

우리는 Store를 작성할 때, 필드와 메소드만 생각하면 된다. 관심사의 분리가 더욱 잘 되었다.

store를 작성한다.

import { singleton } from 'tsyringe';

import { Store, Action } from 'usestore-ts';

@singleton()
@Store()
export default class CounterStore {
  count = 0;

  @Action()
  increase(step = 1) {
    this.count += step;
  }

  @Action()
  decrease() {
    this.count -= 1;
  }
}

작성한 store를 사용하기 위한 커스텀 훅을 작성한다.

import { container } from 'tsyringe';

import { useStore } from 'usestore-ts';

import CounterStore from '../stores/CounterStore';

export default function useCounterStore() {
  const store = container.resolve(CounterStore);
  return useStore(store);
}

store를 작성할 때 Action 데코레이터 사용시 주의할 점이 있다. Action 데코레이터는 메소드 내부의 작업이 끝나고, publish를 해주는데 여기서 비동기 처리는 기다려주지 않는다. 따라서 만약에 메소드 내부에서 비동기 처리를 하게 된다면, 비동기 처리가 끝날때 까지 기다리지 않고 publish를 하게 되는 것이다. 따라서 아래와 같이 코드를 쪼개줘야 한다.

@singleton()
@Store()
class PostStore {
  posts: Post[] = [];

  async fetchPosts() {
    this.startLoading();

    const posts = await fetchPosts();

    this.completeLoading(posts);
  }

  @Action()
  startLoading() {
    this.posts = [];
  }

  @Action()
  completeLoading(posts: Post[]) {
    this.posts = posts;
  }
}

Last updated