본문 바로가기

공부기록/[강의노트] Udemy React 완벽가이드 201~300

# 255 [udemy React 완벽 가이드 노트] Redux toolkit에서 여러개의 reducer 사용해보기

로그인 버튼을 누르면 사용자 인증 상태에 있게 하고 

로그아웃 버튼을 누르면 사용자 미인증 상태가 되게 해보자

 

 

이것은 Header 컴포넌트와 Auth 컴포넌트,

UserProfile 컴포넌트와 관련이 있다. 

 

기존의 index.js 파일에

initialState에 isAuthenticated 속성과 

createSlice부분의 reducers에 메서드를 추가할 수 있을 것이다. 

기술적으로는 작동하지만 이건 의미적으로 맞지 않다. 

counter과 login은 관련이 없기 때문이다.

 

새로운 Slice를 추가하는 것이 맞을 것이다. 

 

 

 

새로운 slice 추가하기

 

 

const initialAuthState = {
  isAuthenticated: false,
};

const AuthSlice = createSlice({
  name: "authentication",
  initialState: initialAuthState,
  reducers: {
    login(state) {
      state.isAuthenticated = true;
    },
    logout(state) {
      state.isAuthenticated = false;
    },
  },
});

 

 

주의 : 리덕스 스토어는 하나밖에 없다.

 

 

const store = configureStore({
  reducer: counterSlice.reducer,
});

 

이 스토어에는 한개의 reducer밖에 없다..

그러면 객체로 전달하자. 

 

 

const store = configureStore({
  reducer: {
    counter: counterSlice.reducer,
    auth: AuthSlice.reducer
  }
});

 

reducer 객체안에 원하는 key로 여러개를 전달할 수 있게 된다. 

나중에 이 리듀서들이 자동으로

하나의 메인 리듀서로 합쳐지게 될 것이다.

 

그리고 actions도 authActions를 만들어 export해주자

 

 

export const authActions = AuthSlice.actions;

 

 

 

 

 

이제 지금과 이전시간에 배웠던 것을 토대로

다른 컴포넌트에서 사용할 수 있다.