Pinia

Pinia 2

Hoon1994 2022. 8. 30. 14:18

Pinia Logo

Pinia의 State 사용 방법

Vuex를 사용할 때는 state의 상태 값을 mutation을 통해 변경해줘야 했으며, 직접적으로 state의 값을 변경하는 경우 오류를 발생시킨다.

Vuex와 다르게 Pinia는 mutation이 없는데, state를 어떻게 변경하는지 알아보자.

 

export const useCounterStore = defineStore('counter', () => {
    const count = ref(2);
    const name = ref('ethan');
    const doubleCount = computed(() => count.value * 2);
    function increment () {
    	// Change state value
        count.value++
    };

    return { count, name, doubleCount, increment };
})

 

어려울 것도 없고, 특별한 것도 없다. mutation이 없기 때문에 일반 변수 다루듯이 state의 값을 변경하면 된다. 

 

아래처럼도 state 변경이 가능하다.

 

const { count } = storeToRefs(counterStore);
const { $patch } = counterStore;

const counterIncrement = () => {
  $patch({ count: count.value + 1 });
}

 

개인적으로는 store에 state 값을 변경하는 함수를 따로 두고, 가져와서 호출하는 게 더 간결하고 깔끔한 것 같다.

 

또한, state의 값을 모두 초기화 시키는 함수도 Pinia에서 제공해준다.

 

    const counterStore = useCounterStore();
    const initState = JSON.parse(JSON.stringify(counterStore.$state));
    const { $patch } = counterStore;

    counterStore.$reset = () => $patch(initState);

    const counterStoreReset = () => counterStore.$reset();

 

$reset에 초기화 해주는 함수를 넣어주는건데, 굳이 $reset에 넣는 이유는 잘 모르겠다. 이거는 좀 알아봐야 할 듯 하다.

Vuex의 상태를 구독하는 subscribe처럼 Pinia도 상태를 구독할 수 있다.

 

    counterStore.$subscribe((mutation, state) => {
      console.log(mutation);
      console.log(state);
    })

 

mutation이 사라졌는데 공식 문서에 파라미터 이름을 mutation으로 해두어서 조금 헷갈렸다.

mutation type, payload, stateId 등 속성이 있는데 해당 값을 통해 어떤 방식으로 state의 값이 변경되었는지 확인이 가능하다.

 

 

첫번째는 store의 $patch 메소드를 사용한거고, 두번째, 네번째 줄은 state의 값이다.
세번째는 함수를 직접 생성해서 state를 변경했을 때다. patch object, direct로 구분되는듯 하다.

 

$subscribe 같은 경우 호출한 컴포넌트에 바인딩되기 때문에, 컴포넌트가 해제될 경우 구독 또한 취소된다.

만약 이를 원하지 않을 경우, detached 옵션을 추가하면 된다.

 

    counterStore.$subscribe((mutation, state) => {
      console.log(mutation);
      console.log(state);
    },{ detached: true })

 

또한 watch를 사용하여 pinia의 모든 상태를 감시할 수 있다.

 

watch(
  pinia.state,
  (state) => {
    // persist the whole state to the local storage whenever it changes
    localStorage.setItem('piniaState', JSON.stringify(state))
  },
  { deep: true }
)

 

 

다음에는 getter에 대해 알아보는 포스팅을 올릴 예정이다.