주스탄드에서 getter를 사용 가능?

쑹춘·2023년 4월 13일
0

주스탄드와 게터

목록 보기
3/3

그렇게 할 수 없다, 함수로 작성하시오.


아래와 같이 getter member는 동작하지 않는다.

import { create } from "zustand";

type NameStore = {
  firstName: string | null,
  lastName: string | null,
  get fullName(): string | null,
};

const useNameStore = create((set, get) => ({
  firstName: null,
  lastName: null,
  get fullName() {
    const { firstName, lastName } = get();
    return [firstName, lastName].join(" "); 
  },
}));

const nameStore = useNameStore();
nameStore.getState().fullName; // is ""
nameStore.setState({ firstName: "sung", lastName: "park" });
nameStore.getState().fullName; // expected "sung park", received ""

2020년 8월에 이런 주스탄드 이슈 포스트가 있다. 오리지널 포스트는 getter 얘기를 딱히 하진 않았는데, 내가 검색을 했던 건 zustand, getter 키워드였기 때문에 이슈 클로징 코멘트에 달린 다이시 멘션이 걸린 것이다.

Now, reading the thread from the beginning again, I noticed I misunderstood the original issue. The OP never said object getters. So, the above example would be the answer.

안된다는 것은 잘 알겠다.

I don't think getters work because of Object.assign(). Once you setState({ user }), signedIn becomes a boolean value. I didn't try it, so correct me if I'm wrong.

이란 것을 보면 처음에 작성한 initial value의 평가 값을 가지고 어디 객체에 저장하고 있는가 보다 싶었다.

주스탄드 코드를 열어보면 (열어볼 때마다 드는 생각인데, zustand는 내부 코드가 아주 간결하고 기분이 좋다.) 아마 여기쯤 될 것이다. 실험을 해볼까?

const o = { name: "sun", get proxied() { return this.name; } };
o; // { name: 'sun', proxied: [Getter] }
o.proxy; // 'sun'
const shallowClonedO = Object.assign({}, o);
shallowClonedO; // { name: 'sun', proxied: 'sun' }

명제 a. object getter는 Object.assign으로 옮길 때 죽는다. 왠지 그러라고 있는 정적 메소드도 아니고, 아무튼 (java에서 그러는 것처럼) (싫지만) get- 으로 시작하는 메소드를 작성하자.

그전에 나는 왜 getter를 쓰고 싶은걸까?

profile
성천

0개의 댓글