ReduxStudy(Subscription)

이승훈·2022년 10월 25일
0

TIL

목록 보기
14/31
post-thumbnail

Subscription

import { createStore } from "redux";

const add = document.getElementById('add');
const minus = document.getElementById('minus');
const number = document.querySelector('span');

const countModifier = (count = 0, action) => {
  console.log(count);
  if(action.type === "ADD") {
    return count + 1;
  } else if(action.type === "MINUS") {
    return count - 1;
  } else {
    return count;
  }
};

const countStore = createStore(countModifier);

const handleAdd = () => {
  countStore.dispatch({ type: "ADD" });
}

const handleMinus = () => {
  countStore.dispatch({ type: "MINUS" });
}

add.addEventListener("click", handleAdd);
minus.addEventListener("click", handleMinus);

이제 버튼을 클릭함에 따라 count를 modify할 수 있다.

이제 이 수정한 count를 index.html에서 notified할 수 있게 해야한다.

이 때 사용하는것이 store의 subscribe 메소드 이다.

subscribe는 우리에게 store안의 변화들을 알 수 있게 해준다.

import { createStore } from "redux";

const add = document.getElementById('add');
const minus = document.getElementById('minus');
const number = document.querySelector('span');

const countModifier = (count = 0, action) => {
  if(action.type === "ADD") {
    return count + 1;
  } else if(action.type === "MINUS") {
    return count - 1;
  } else {
    return count;
  }
};

const countStore = createStore(countModifier);

const onChange = () => {
  console.log("변화가 감지되었다!!")
}

countStore.subscribe(onChange);

const handleAdd = () => {
  countStore.dispatch({ type: "ADD" });
}

const handleMinus = () => {
  countStore.dispatch({ type: "MINUS" });
}

add.addEventListener("click", handleAdd);
minus.addEventListener("click", handleMinus);

위처럼 코드를 작성해줄경우 store에 있는 data에 변동이 있을 때 마다 subscribe 메소드안의 콜백함수인

onChange함수가 호출/실행된다.

그렇다면 아래처럼 span의 innerText에 countStore.getState()를 넣어줌으로서 숫자를 브라우저에 표시해줄 수 있게 된다.

import { createStore } from "redux";

const add = document.getElementById('add');
const minus = document.getElementById('minus');
const number = document.querySelector('span');

const countModifier = (count = 0, action) => {
  if(action.type === "ADD") {
    return count + 1;
  } else if(action.type === "MINUS") {
    return count - 1;
  } else {
    return count;
  }
};

const countStore = createStore(countModifier);

const onChange = () => {
  number.innerText = countStore.getState();
} <-여기여 여기

countStore.subscribe(onChange);

const handleAdd = () => {
  countStore.dispatch({ type: "ADD" });
}

const handleMinus = () => {
  countStore.dispatch({ type: "MINUS" });
}

add.addEventListener("click", handleAdd);
minus.addEventListener("click", handleMinus);

짚고넘어가자면

우리의 data를 수정하는 유일한 곳은 reducer 함수다.

profile
Beyond the wall

0개의 댓글