RTK, Immer.js

박요셉·2024년 5월 27일
0

React

목록 보기
8/15

아 정리한거 날라갔다 아..

import { createSlice } from "@reduxjs/toolkit";
import { produce } from "immer";

const initialState = {
  count: 0,
  school: {
    classes: {
      students: [{ 이름: "진영", 나이: "3" }],
    },
  },
};

function counterReducer(state, action) {
  if (action === "진영나이바꾸기") {
    // immerjs를 안쓴다.
    // const newState = {...state, school: {...state.school, class : {...state.school.class, students: state.school.class.students.map(student => student.이름 === '진영' ? student.나이 === 1 : student)}}}

    // immer.js를 쓴다.
    const nextState = produce(state, (draft) => {
      // 두번째 인자로 들어오는 함수는 관습적으로 recipe라고 부른다.
      // draft.school.class.students.find(student => student.name === '진영').~~~
    });

    return nextState;
  }
  //이머를 왜 공부해야ㅕ대???? 툴킷엔 있는데??
  // 리액트 쿼리를 쓰던, 주스텐드를 쓰던 이머 제이에스를 알아두면 좋다.
}

const counterSlice = createSlice({
  initialState,
  name: "counter",
  reducers: {
    increment: (state, action) => {
      // console.log(action.type) => counter/increment
      const value = action.payload;

      //  return {...state, count: state.count + value};
      state.count = state.count + value;
    },
    decrement: (state, action) => {
      const value = action.payload;

      state.count -= value;
    },
    update진영나이: (state, action) => {
      state.school.class.students.find(
        (student) => student.이름 === "진영"
      ).나이 = 15;
    },
  },
});

export const countReducer = counterSlice.reducer;

// 이름은 actions지만 사실은 action creator들(함수)이 나온다
export const { increment, decrement } = counterSlice.actions;
profile
개발자 지망생

0개의 댓글