Redux-toolkit 기초

걸음걸음·2023년 4월 11일
0

Project

목록 보기
4/6

일단 내가 당장 쓰기 위해, 내가 이해하고 사용하는 방법을 적는 글
YesOrNo 프로젝트에 적용했던 걸 기초로 작성
추후 여러 슬라이스를 쓸 경우 / 타입스크립트 적용 등의 케이스 추가 예정

설치

npm i @reduxjs/toolkit react-redux

JavaScript

store

Slice

import { createSlice } from '@reduxjs/toolkit';

const dataSlice = createSlice({
  name: 'dataSlice', // slice의 이름
  initialState: { answer: '', image: '' },
  // 가장 처음의 데이터 상태.
  reducers: {
    // 해당 데이터를 다루는 함수
    set: (state, action) => {
      // state : 현재 데이터 상태
      // action : type과 payload를 받음. 이 경우 type은 'dataSlice/set'
      // payload는 해당 함수를 통해 전달받은 데이터
      state.answer = action.payload.answer;
      state.image = action.payload.image;
    },
  },
});

export default dataSlice;
export const { set } = dataSlice.actions;

Store

import { configureStore } from '@reduxjs/toolkit';
import dataSlice from './dataSlice';

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

export default store;

데이터를 Provider로 전달.

//index.js
<Provider store={store}>
  <App />
</Provider>

적용

// App.js
function App() {
  const [your, setYour] = useState('');
  const dispatch = useDispatch(); // dispatch 지정
  
  
  const answer = useSelector((state) => {
    return state.data.answer;
  });
  // store에서 data로 지정한 reducer의 state값 받아오기
  const urlImg = useSelector((state) => {
    return state.data.image;
  });
  
  const getData = async () => {
    let temp = await getDataAPI();
    dispatch(set({ answer: temp.answer, image: temp.image }));
    // dispatch(실행할 함수(payload로 전달할 값))
  };
  return (
    <AppBox answer={answer}>
    </AppBox>
  );
}

export default App;

TypeScript

store

slice

import { createSlice } from '@reduxjs/toolkit';
import { Todo } from '../models/todo';

type TodoState = Todo[];
// initialState의 타입 지정

const initialState: TodoState = [];

export const todoSlice = createSlice({
  name: 'todo',
  initialState,
  reducers: {
    set: (state, action) => {
      // state = [...action.payload];
      state.push(...action.payload);
    },
    add: (state, action) => {
      state.push(action.payload);
    },
    del: (state, action) => {
      return (state = state.filter((todo) => todo.id !== action.payload));
    },
    clear: (state, action) => {
      return (state = state.map((todo) =>
        todo.id === action.payload ? { ...todo, type: 'clear' } : todo
      ));
    },
    update: (state, action) => {
      const { id, type } = action.payload;
      return (state = state.map((todo) =>
        todo.id === id ? { ...todo, type: type } : todo
      ));
    },
  },
});

export const { set, add, del, clear, update } = todoSlice.actions;
export default todoSlice.reducer;

store

import { configureStore } from '@reduxjs/toolkit';
import todoReducer from './todoSlice';

const store = configureStore({
  reducer: {
    todo: todoReducer,
  },
});

export default store;
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
// RootState와 AppDispatch로 store의 타입 추론

적용

//App.tsx
  const dispatch = useDispatch();
  const todoData = useSelector((state: RootState) => {
    return state.todo;
  });
  const importantData = useSelector((state: RootState) => {
    return state.todo.filter((ele) => ele.type === 'important');
  });
  const normalData = useSelector((state: RootState) => {
    return state.todo.filter((ele) => ele.type === 'normal');
  });
  const clearData = useSelector((state: RootState) => {
    return state.todo.filter((ele) => ele.type === 'clear');
  });
profile
꾸준히 나아가는 개발자입니다.

0개의 댓글