[TIL] jsx 아닌 파일에서 redux 읽고, dispatch 하기

햄스터아저씨·2022년 2월 8일
0

원래 리덕스는 리액트와 무관하게 사용할 수 있다.
그런데 나의 경우, useDispatch, useSelector 같은 리액트 hook을 주로 사용하다보니, hook 을 쓸 수 없는 일반 js, ts 파일에서의 리덕스 사용법을 까먹게 되어... 방법을 기억하려고 남기는 글

우선 Redux를 사용하기 위해 아래와 같이 createStore 함수를 썻다고 가정한다

import { createStore } from "redux";

// 중간 코드 생략

const store = createStore(
  rootReducer,
  // 생략
);

export { store };

그러면 어디서든 store 를 아래와 같이 가져와 내용을 읽을 수 있다.


import { store } from "@src/Store";

export const isValid = (from: string): boolean => {
  return store.getState().roomlist.usage.roomCnt >= 50;
};

Dispatch 도 다음과 같이 할 수 있다.


import { store } from "@src/Store";
import { actions } from "@store/Room"; //export const { actions } = MySlice;

export const update = () => {
  store.dispatch(actions.testCall());
};
profile
서버도 하고 웹도 하고 시스템이나 인프라나 네트워크나 그냥 다 함.

0개의 댓글